If you know that you will choose a template type, you will know almost everything you need for auto type output. Because automatic type inference works like template type inference.
When a variable is declared using auto , then auto acts like T in the template, and the type specifier acts like the type of the parameter:
const auto i = 20;
Translate to:
template<typename T> void func(const T param) { ... }
And with a link:
const auto& j = i;
Translated to:
template<typename T> void func(const T& param)
With pointers, it's the same thing:
auto* v1 = &x;
becomes
template<typename T> void func(T* param)
Since x is int , then auto* == int* .
And auto* v2 = px; also int*
Now the third one has:
auto* v3 = &px;
It becomes int** , as you take the address of the pointer.
template<typename T> void func(T** param)
A convenient way to see the type of car is to use what others have mentioned, the typeid() function.
But I like to use <boost/type_index.hpp> to display the type correctly:
#include <iostream> #include <boost/type_index.hpp> using namespace std; using namespace boost::typeindex; int main() { int x = 64; int* px = &x; auto* v1 = &x; auto* v2 = px; auto* v3 = &px; cout << type_id_with_cvr<decltype(v1)>().pretty_name() << '\n'; cout << type_id_with_cvr<decltype(v2)>().pretty_name() << '\n'; cout << type_id_with_cvr<decltype(v3)>().pretty_name() << '\n'; }
What outputs:
int* int* int**
There is one important difference between automatic type deduction and template type inference, namely std::initializer_list<>
Consider the following examples:
auto i = 1; // int auto j(1); // int auto k = { 1 }// std::initializer_list<int> ! auto l { 1 } // std::initializer_list<int> !
As you can see, using a combination initializer with a car can be a problem.
However, you can manually write the type in front of curly braces to make sure the type is correct, but I donβt see the point:
auto i = int{ 1 };
There are new automatic rules that are already implemented in Clang 3.8, which allows you to use direct list initialization with auto (upcoming standard)