Boost logo

Boost :

From: Steven Kirk (steven.kirk_at_[hidden])
Date: 2001-02-23 03:38:27


Hello all,

I've just uploaded a file, poly_iterator.zip to the boost file area. I'm not
sure how useful people will consider it to be, but it helps considerably
with a problem that I keep encountering.

The library (actually just one file at the moment) greatly simplifies
iteration over an inheritence heirarchy. A base class specifies the
iteration interface, usually in the form of pure virtual functions, to
return a polymorphic iterator provided by this library.

This iterator itself contains a pointer to an implementation which wraps a
normal iterator. This poly_iterator library automates the creation of
the iterators and the implementation by means of templates.

Does that make sense? An example may make this a little clearer. This is
test.cpp, included in the zip file:

// The base class defines the iteration interface and the iterator type.
class Base {
public:
    typedef boost::poly_forward_iterator<int> iterator;

    virtual iterator begin() = 0;
    virtual iterator end() = 0;
    virtual void insert(int n) = 0;
    virtual void erase(const iterator &i) = 0;
};

// This class implements the collection as a vector.
class VectorImpl : public Base {
    std::vector<int> c;
public:
    virtual iterator begin()
        { return boost::make_poly_iterator<iterator>(c.begin()); }
    virtual iterator end()
        { return boost::make_poly_iterator<iterator>(c.end()); }
    virtual void insert(int n)
        { c.push_back(n); }
    virtual void erase(const iterator &i)

 c.erase(boost::crack_poly_iterator<std::vector<int>::iterator>(i)); }
};

// This class implements the collection as a list.
class ListImpl : public Base {
    std::list<int> c;
public:
    virtual iterator begin()
        { return boost::make_poly_iterator<iterator>(c.begin()); }
    virtual iterator end()
        { return boost::make_poly_iterator<iterator>(c.end()); }
    virtual void insert(int n)
        { c.push_back(n); }
    virtual void erase(const iterator &i)

       { c.erase(boost::crack_poly_iterator<std::list<int>::iterator>(i)); }
};

Here you can see the interface, defined in class Base, and two
implementations, one using a std::vector and one using a std::list. The
'make_poly_iterator' function is a helper function that automatically wraps
the provided iterator and returns a polymorphic iterator of the specified
type. 'crack_poly_iterator' does the reverse, and retreives the underlying
iterator from the polymorphic iterator.

The only polymorphic iterator type currently implemented is a forward,
non-const iterator. I think bi-directional and const versions will be
required as well.

Is this of any use? How will I improve it? (there's a lot to be done I know)


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk