Template argument deduction for const argument

Let's pretend that

template <typename T>
void foo(T a)
{
    a = 10;
}

int main()
{
    const int a = 5;
    foo(a);
}

      

Why is T being output as int and not const int, why would I change the in function? How does deduction work in this case?

Here's a working example.

+3


source to share


2 answers


Why is T being output as int and not const int, why can I change in a function?

Because you are passing by value and getting by value (no reference). According to linguistic grammar, such an inference will always result in the precedence being non-const over const

.
For a better understanding, try typing in C ++ 11 code and typing typeid

:

const int a = 5;  // `a` typeid is `const int`
auto b = a;    // `b` typeid is `int`

      

How does deduction work in this case?



If you want a

not to change and refer to the const

state of the passed object, then get by reference in the function. i.e.

template<typename T>
void foo (T& a) 
{
  a = 10; // this will result in error if a `const int`
}

      

[Note. Passing a literal will never work with a label.]

+2


source


Why const

does the fact that an object outside a function matters to an inner function? He gets his own copy of the object, so he can choose for himself whether to treat this copy as const

or not. Changing a function a

within a function will not affect the external object. This is the reason why the upper levels of cv qualifiers are ignored for type inference.



If you want the parameter to be const

, you need to ask for it.

+6


source







All Articles