Boost logo

Boost Users :

Subject: [Boost-users] Iterators and subclasses
From: Swerts, Benjamin (Benjamin.Swerts_at_[hidden])
Date: 2009-10-12 08:19:45


Hello all,

I'm trying to create a base class that provides 2 iterators (begin/end).
These will be used to iterate over data structures that will be provided
by subclasses. These data structures are completely unrelated. Normally
this can be solved using virtual functions but the problem is that
iterators are normally returned by value so I cannot go that route.

My concrete problem:

struct Point { int x, y; };
class PointIterator : public boost::iterator_facade<PointIterator, const
Point, boost::random_access_traversal_tag, Point>;
class PointCollection
{
  public:
    typedef PointIterator const_iterator;
    const_iterator begin();
    const_iterator end();
};

>From the PointCollection base class I want to derive concrete
implementations:

class Collection1 : public PointCollection
{
  public:
    Collection1(char* data, size_t size) : data_(data), size_(size) {};
  private:
    char* data_;
    size_t size_;
};

Collection1 would return a Point with x = data_[index] and y = index *
1000, for example. Other subclasses might contain 2 vectors or just
generated values.
In my first attempt I tried to subclass the iterator too and make it
return the correct Point when the iterator is dereferenced. As the
iterators are returned by value, however, the subclass was sliced right
off.
An iterator-less solution is easy:

class PointCollection
{
  public:
    virtual Point getPoint(size_t index) const = 0;
    virtual size_t size() const = 0;
};

Easily subclassed but no iterator support. How would I solve this
problem with iterators? Should I implement another iterator over them
that doesn't know about the actual types of the iterators? Can
indirect_iterator help me in any way?
Thanks a lot in advance!

Greets,

        Ben


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net