I\'m currently trying to understand the intrinsics of iterators in various languages i.e. the way they are implemented.
For example, there is the following class ex
The C++ standard library does not use polymorphism and inheritance in its implementation of iterators; instead, it uses C++ template metaprogramming and the notion (but not formal syntax*) of "concepts".
Essentially, it will work if the interface for your iterator class adheres to some set of requirements. This set of requirements is called a "concept". There are several different iterator concepts (see this page for a list of all of them), and they are hierarchical. The basics of creating a compatible C++ iterator is to make your interface conform to the concept. For a simple iterator that goes only in the forward direction, this would require:
value_type
for the value that results from dereferencing your iterator.reference_type
, which is the reference type for the corresponding value type.pointer
, which is a pointer type for the corresponding value type.iterator_category
, which needs to be one of input_iterator_tag, forward_iterator_tag, bidirectional_iterator_tag, or random_access_iterator_tag, depending on your traversal mechanism.difference_type
indicating the result of subtracting two different iterators.const value_type& operator*()const
function for dereferencing the iterator.value_type& operator*()
function if your iterator can be used to manipulate the value.operator++()
and operator++(int)
functions) for seeking forward.difference_type operator-(const type_of_iterator&)
If you choose one of the more advanced iterator categories, you may also need to specify a decrement and plus operator in order to be able to seek backwards or to seek an arbitrary distance.
*The C++ standard library uses concepts so frequently in an informal way, that the C++ standards commitee sought to introduce a formal mechanism of declaring them in C++ (currently they exist only in documentation of the standard library, and not in any explicit code). However, persistent disagreements on the proposal led to it being scrapped for C++0x, although it will likely be reconsidered for the standard after that.