auto
and decltype
Explained,
by Thomas Becker
about me
auto
Keyword: The Basics
Consider the following code snippet:
std::vector<int> vect; // ... for( std::vector<int>::const_iterator cit = vect.begin(); cit != vect.end(); ++cit ) { std::cout << *cit; }Perfectly fine, we all write code like this or similar all the time. Now let us consider this instead: std::vector<int> vect; // ... for( std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it ) { std::cin >> *it; }When writing this code, you should be getting slightly annoyed. The variable it is of the exact
same type as the expression vect.begin() with which it is being initialized, and the
compiler knows what that type is. Therefore, for us to have to write std::vector<int>::iterator
is redundant. The compiler should use this as the default for the type of the variable it .
And that is exactly the issue that the auto keyword addresses. In C++11, we can write:
std::vector<int> vect; // ... for(auto it = vect.begin(); it != vect.end(); ++it) { std::cin >> *it; }The compiler will use the type of the initializing expression vect.begin() , which is
std::vector<int>::iterator , as the type of the variable it .
This sounds easy enough, but it's not quite the full story on |