Another example
suggest changeLet’s say we have a vector:
std::vector<int> intVector;
And we want to declare an iterator for this vector. An obvious idea is to use auto. However, you may need to declare an iterator variable and not initialize it. We would do:
std::vector<int>::iterator iter;
However, with decltype it becomes easy and less error-prone (if the type of intVector changes).
decltype(intVector)::iterator iter;
Alternatively:
decltype(intVector.begin()) iter;
In the second example, the return type of begin is used to determine the actual type, which is std::vector<int>::iterator.
If we need a const_iterator, we just need to use cbegin:
decltype(intVector.cbegin()) iter; // vector<int>::const_iterator
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents