It is often desirable for a template function to find out what is the most specific category of its iterator argument, so that the function can select the most efficient algorithm at compile time. To facilitate this, the library introduces category tag classes which are used as compile time tags for algorithm selection. They are: input_iterator_tag, output_iterator_tag, forward_iterator_tag, bidirectional_iterator_tag and random_access_iterator_tag. For every iterator of type Iterator, iterator_traits<Iterator>::iterator_category must be defined to be
the most specific category tag that describes the iterator’s behavior.
1 2 3 4 5 6 7
| namespace std {
struct input_iterator_tag {};
struct output_iterator_tag {};
struct forward_iterator_tag: public input_iterator_tag {};
struct bidirectional_iterator_tag: public forward_iterator_tag {};
struct random_access_iterator_tag: public bidirectional_iterator_tag {};
} |
2 [Example: For a programdefined iterator BinaryTreeIterator, it could be included into the bidirectional iterator category by specializing the iterator_traits template:
1 2 3 4 5 6
| template<class T> struct iterator_traits<BinaryTreeIterator<T> > {
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef bidirectional_iterator_tag iterator_category; |
};
Typically, however, it would be easier to derive BinaryTreeIterator<T> from
iterator<bidirectional_iterator_tag,T,ptrdiff_t,T*,T&>. —end example]
Partager