I looked at STL’s forward iterator. I don’t see any virtual functions anywhere. If I have a library that wants a forward iterator of strings how can I allow the function to take any forward iterator that returns strings? Is there anything in the standard library I can use?
I looked at STL’s forward iterator. I don’t see any virtual functions anywhere. If
Share
There are no virtual methods as they are not meant to be used polymorphically (in the common sense of runtime polymorphism) but rather through templates (static polymorphism). The common approach is having the function that takes the iterators templatized on the type of the iterator. You can find many examples in the STL algorithm header:
In your particular case:
The additional restriction that it has to refer to strings can be implemented in term of type traits and enable_if:
Using typetraits from c++0x, but the
enable_ifandis_sameare available in boost if you need them in a compiler that does not have support for them.If you need to be able to switch the types of iterators at runtime, you might want to look into
any_iteratorthat performs type erasure on the specific iterators providing a runtime polymorphic interface. It is described in the article On the Tension Between Object-Oriented and Generic Programming in C++, the implementation can be found in Adobe STLab.