when I can more easily write
I don't see what information or convenience iterator_traits provides.
You can't do this with pointers, but you can easily define
iterator_traits for pointers, and the standard library do this.
With traits you could use things like
std::iterator_traits< int * >::difference_type
i.e., treat pointers as iterators.
Consider the following:
You want to write a generic function which takes some iterator range
and computes something inside which requires for example the value type.
Now you define for example
Iterator::value_type somefunction(Iterator first, Iterator last)
Iterator::value_type mean = (*first + *last)/2.0;
Looks OK ??? Pointers are iterators ??? Yep.
But your compiler will choke on this if you call it like this
T answer = somefunction(first, second);
Why?? Because It does not know how to apply the :: scope operator on a
given pointer type T* (You do fine using dereferencing
like *first, but what is it's type ??? You can not know...)
So, the compiler needs som help in doing the obvious (for humans obvious
at least..). And the only way to do it is through an indirection over the
The trick is using
typename iterator_traits<Iterator>::value_type mean = ...
because a suitable specialization
template <class T>
typedef T value_type
let the compiler know what the value type of a T* is, and the most general
template struct iterator_traits points of course to the
Iterator::value_type as you would like to use it directly.
The reason is also to be able to treat ordinary pointers as iterators in
For details, see please
"Generic Programming and the STL" Matthew H. Austern,
a really good book on this topic.
Cheers, Marc Cromme