Virtual iterator?

I looked at the STL iterator. I do not see any virtual functions anywhere. If I have a library that wants a forward iterator of strings, how can I let a function accept any forward iterator that returns strings? Is there anything in the standard library that I can use?

+4
source share
4 answers

There are no virtual methods, because they should not be used polymorphically (in the general sense of polymorphism at runtime), but rather through patterns (static polymorphism). A general approach is a function that accepts iterators templatized to an iterator type. You can find many examples in the header of the STL algorithm:

template <class InputIterator, class Distance> inline void distance(InputIterator first, InputIterator last, Distance& n); 

In your particular case:

 template <class ForwardIterator> // or InputIterator or whatever your needs are void acceptIterators( ForwardIterator start, ForwardIterator end ); 

An additional restriction that it must refer to strings can be implemented in terms of type traits and enable_if:

 template <class ForwardIterator> std::enable_if< std::is_same< std::string, typename iterator_traits<ForwardIterator>::value_type > > void acceptIterators( ForwardIterator start, ForwardIterator end ); 

Using typetraits from C ++ 0x, but enable_if and is_same are available in boost if you need them in a compiler that doesn't have support for them.

If you need to switch the types of iterators at runtime, you may need to look at any_iterator , which any_iterator styles on specific iterators that provide a polymorphic interface at runtime. In the article "On the tension between object-oriented and general programming in C ++", an implementation can be found in Adobe STLab .

+6
source

You can write your own iterator and use it like:

 std::for_each( make_myiterator(c.begin), make_myiterator(c.end), do_some() ); 

You can inherit from std::iterator or check Enlarge Iterator Facade - this will help you write your own iterator.

+1
source

The usual way is to create functions that use iterator template functions. This is what the standard library does.

0
source

If you want to accept any iterator, for example, strings you need to use patterns. There is no top-level iterator class that inherits all other iterators.

Writing compatible C ++ iterators can be a pain, but Boost.Iterators helps you if you're not afraid of patterns. There is an example of using iterator_facade to create a simple iterator that you should pay attention to. Boost.Iterators is a header-only library, so there is no need to link anything to your application / library.

0
source

All Articles