C++ decltype Another example


Let's say we have vector:

std::vector<int> intVector;

And we want to declare an iterator for this vector. An obvious idea is to use auto. However, it may be needed just declare an iterator variable (and not to assign it to anything). We would do:

vector<int>::iterator iter;

However, with decltype it becomes easy and less error prone (if type of intVector changes).

decltype(intVector)::iterator iter;


decltype(intVector.begin()) iter;

In second example, the return type of begin is used to determine the actual type, which is vector<int>::iterator.

If we need a const_iterator, we just need to use cbegin:

decltype(intVector.cbegin()) iter; // vector<int>::const_iterator