In an algorithm, I can determine the value_type directly from the iterator via iter::value_type. Why do algorithms use iterator_traits to do the same?
#include <iostream>
#include <vector>
#include <iterator>
#include <typeinfo>
using namespace std;
template<typename iter>
void for_each(iter first, iter end)
{
cout << "container value type: "
<< typeid(typename iter::value_type).name()
<< endl;
cout << "container value type: "
<< typeid(typename iterator_traits<iter>::value_type).name()
<< endl;
}
int main()
{
vector<int> v1;
for_each(begin(v1), end(v1));
return 0;
}
Output:
container value type: i
container value type: i
For a type
iteratorto be an iterator, it is not necessary to have aniterator::value_typealias. For example, every pointer is an iterator, namely a ContiguousIterator. The user might write:Your code accepting iterators is expected to work with such a function call. Pointers aren't the only problem though:
std::iterator_traitsis a very old construct from C++98, and back in those days, you weren't able to obtain information such as thevalue_typeof an iterator withdecltype(), becausedecltypedidn't exist. Nowadays, you could write something like:for some iterators, but not all.
Be careful, the
value_typecan be customized in two ways that break the above code:iterator::value_typetype alias, whichstd::iterator_traitswill look forstd::iterator_traits<iterator>yourselfBecause these customization points exist, you must always use
std::iterator_traitswhen accessing type information about an iterator. Even in situations wheredecltypeorautolook okay, your code could be incorrect becausestd::iterator_traitswas specialized for the iterator you're working with.See also: What is the design purpose of iterator_traits?