Boost logo

Boost Users :

Subject: Re: [Boost-users] Iterators and subclasses
From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2009-10-12 15:01:19


Swerts, Benjamin wrote:
> 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;
> };

Can't your iterator just hold on to a "container" base class ref, an
incrementable index and call the above virtual method in the iterator's
deref implementation?

Jeff


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