Search code examples
c++c++11autotype-deduction

What the type is auto & x = const int *?


In a main function, I created a variable of const int pointer, assign it to a variable declared by auto&. Then using the decltype(x) to check the type. I expected the type is const int*. But is_same returns false.

int main()
{
    int a = 10;
    const int * cp_val= &a;
    auto& x = cp_val;
    bool is_const_int_ptr = std::is_same<decltype(x), const int *>::value; // returns 0

    // *x = 100; // error: assignment of read-only location '* x'
}

But if I add the following helper function:

#include <boost/type_index.hpp>

template<typename T> 
void print_type(T)
{cout << "type T is: "<< boost::typeindex::type_id_with_cvr<T>().pretty_name()<< '\n';}

In the main, I invoke the function

print_type(x); // It returns int const*

Am I missing something in std::is_same?


Solution

  • Template argument deduction and auto are intimately related: The declaration auto x = e; gives x the same type as f(e) would give to T in an invented function template <typename T> f(T);, and similarly for auto& and f(T&), const auto* and f(const T*), etc.

    Therefore, to get the correct answer from Boost, you need to declare:

    template <typename T> void print_type(T&);
    //                                   ^^^^
    

    The type of x is of course const int*&.