deducing references to const from rvalue arguments

前端 未结 3 1693
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 19:38

Okay, this may seem like a silly question, but here it goes:

template 
void foo(T& x)
{
}

int main()
{
    foo(42);
    // error in pa         


        
3条回答
  •  既然无缘
    2020-12-17 20:12

    Be it template or normal functions, rvalue cannot be passed by reference. (so const T& works but not T&).

    What is preventing C++ to instantiate the foo function template with T = const int instead?

    Suppose, C++ allows and makes T = const int instead. Now after sometime you change foo as,

    template
    void foo (T& x)
    {
      x = 0;
    }
    

    Now compiler has to generate error. For end user the experience will be strange, as for a valid statement like x = 0; it started giving error. That could be the reason that why compiler prevents at the first stage itself!

提交回复
热议问题