I am new to C++ so please bear with me. I am trying to understand STL iterator_traits. In the book "The C++ Standard Library" the structure iterator_traits is defined as follows:
template <class T>
struct iterator_traits{
typedef typename T::value_type value_type
typedef typename T::difference_type difference_type
typedef typename T::iterator_category iterator_category
typedef typename T::pointer pointer
typedef typename T::reference reference
}
So it seems to me that it is re-exposing the subtypes that T
already exposes. Moving ahead further, the book gives an example of how to use it, which is something like the following
template <class MyIterator>
void do_something(MyIterator start, MyIterator end) {
typedef typename iterator_traits<MyIterator>::value_type value_type
value_type v = *start
.....
My question is why do I need this iterator_traits structure here, if the idea was to obtain the value_type
, couldn't I have obtained it from MyIterator
directly ? My confusion seems to arise from my (surely incorrect) understanding that the information of the subtypes have to be sourced from the template <class T>
used to instantiate the iterator_trait. So if you could explain, and preferably with an example why and where would I need iterator_traits that would be very helpful.