Search code examples
c++templatesreferencetype-deduction

Why is reference template argument not deducing const?


I have written following code and for pointer it is showing correct argument type, but when I use reference it is only showing int and no const. why?

template <typename T>
void increment(T& x)
{
    std::cout << "Argument type is : " << typeid(x).name() << std::endl;
    //x = x + 1;
}

template <typename T>
void increment(T* x)
{
    std::cout << "Argument type is : " << typeid(x).name() << std::endl;
    //x = x + 1;
}  

int main()
{
    const int x = 0;
    const int y = x;
    increment(x);
    increment(&y);
}

Output:

Argument type is : int 
Argument type is : int const *

Please, can you explain why const is not shown with reference?


Solution

  • From typeid reference:

    If type is a reference type, the result refers to a std::type_info object representing the referenced type.

    and

    In all cases, cv-qualifiers are ignored by typeid (that is, typeid(T)==typeid(const T))

    (more precisely top-level const) T was of course deduced as const int.


    The standard paragraphs are [expr.typeid]/4 and [expr.typeid]/5