Why is `const T&` not sure to be const?

前端 未结 2 1566
离开以前
离开以前 2020-12-24 05:10
template
void f(T a, const T& b)
{
    ++a; // ok
    ++b; // also ok!
}

template
void g(T n)
{
    f(n, n);
}

int         


        
2条回答
  •  萌比男神i
    2020-12-24 05:32

    I know that there is already an accepted answer which is correct but just to add to it a little bit, even outside the realm of templates and just in function declarations in general...

    ( const T& ) 
    

    is not the same as

    ( const T )
    

    In your example which matches the first, you have a const reference. If you truly want a const value that is not modifiable remove the reference as in the second example.

提交回复
热议问题