I have an Element class which is abstract and I would like to have an
object of the Iterator class to iterate over a range of elements.
I would like to use std::for_each to instrument the iteration, which
forces me to have certain interface on the Iterator class.
struct Element {
virtual ~Element() = 0;
};
struct Iterator {
bool operator!=(Iterator const& ) const;
Iterator& operator++();
// The returned value of this function is the motivation of my
post
// Please, see the comments below the code.
Element& operator*() const;
};
struct Range {
Iterator begin() const;
Iterator end() const;
};
and the client code:
void action(Element const& );
void main()
{
Range range;
std::for_each(range.begin(), range.end(), action);
}
Now, after reading some earlier posts, I get the impression that
experience dictates that iterators should return objects by value. In
my case, however, the Element class is abstract, and therefore I
cannot return an object of that class by value.
I must also point out that in this case, so far clients are not
interested in holding references to values returned by the iterator
beyond the next call to operator*. They simply want to use the objects
and forget about them prior to getting the next object from the
iterator.
Thus, I see no need to return pointers (smart pointers, or what have
you) to objects allocated in the heap. Having said that however, I
should expect that, in the future, new clients may require to hold
references to objects beyond the next call to the operator* on the
iterator. In anticipation of that need, I would like to come up with a
design that, while it does not add lots of unnecessary complexity,
will effortlessly accommodate that future need.
Any comments?