
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
; 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