5

Is it possible to implement an any iterator with boost iterator facade? I don't want to define implementation details in my baseclass

class Base
{
public:
typedef std::vector<int>::iterator iterator;//implementation detail
...
virtual iterator begin()=0;
virtual iterator end()=0;
};

or do i have to write one completely from scratch;

P3trus
  • 51
  • 1
  • 2
  • The way I would probably do it is to define an abstract base class like `Iterator` that acts like a Java or C# iterator, a templated implementation of that for arbitrary iterators, then use Boost.Iterator to wrap an iterator interface on top of any `Iterator`. Do you want me to try to sketch out pseudocode for that? – Jeremiah Willcock Feb 22 '11 at 17:13
  • 1
    You can find one at http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html – UncleBens Feb 22 '11 at 23:03

2 Answers2

9

The code you've posted has fixed the type of iterators returned from Base and all it's implementantions to std::vector<int>::iterator which is probably not what you want. Jeremiah's suggestion is one way to go with one drawback: you loose compatibility with STL... I know of three implementations of a polymorphic iterator wrapper:

  1. becker's any_iterator (which implements boost::iterator_facade)
  2. the opaque_iterator library (google for it), or
  3. Adobe's very interesting poly library which contains a hierarchy of STL conforming any_iterators.

The problem is harder than it might seem... I made an attempt myself mainly because I needed covariance in any_iterators type argument (any_iterator<Derived> should be automatically convertible to any_iterator<Base>) which is difficult to implement cleanly with STL like iterators. A C# like Enumerator<T> is easier to implement(*) (and imho generally a cleaner concept than STL-like pairs of iterators) but again, you "loose" the STL.

(*) = without 'yield' of course :-)

Paul Michalik
  • 4,331
  • 16
  • 18
3

I think this may be what you're looking for:

any_iterator: Type Erasure for C++ Iterators

Here's a snippet from that page::

Overview

The class template any_iterator is the analog to boost::function for iterators. It allows you to have a single variable and assign to it iterators of different types, as long as these iterators have a suitable commonality.

Kev
  • 118,037
  • 53
  • 300
  • 385
c-urchin
  • 4,344
  • 6
  • 28
  • 30