class X {
public:
typedef std::list<int> Container;
// (1)
const Container& GetElements() const;
// (2)
Container::iterator ElementBegin();
Container::iterator ElementEnd();
// (3)
CustomIterator GetElementIterator();
private:
Container m_container;
};
I’m looking for a consistent and clean way of providing iterators to encapsulated containers to the caller. I came up with the three ideas marked in the source code above.
- Provides size(), begin() and end(), all perfect for read access. However, because the returned
Containerreference is const, you’ll only be able to useconst_iterator. Returning the reference non-const is bad, because the container itself could be modified (e.g.clear()). - Provides non-const access to the elements, however we’d often need an own
size()method (likeGetElementCount()).iterator::distance()could be used, but that may be inefficient for some containers (whereoperator++/--is called repeatedly to calculate the distance). - Provides a custom iterator with methods like
next()etc. Still an ownsize()method is required.
I highly bet there’re nicer solutions, so if you know any, I’d be glad to see them.
A mix of (2) and (3) would probably be what I’d do :
It still leaves room to write custom iterators (by changing the
typedefs), but as long as the ones provided by the container are ok, they can be used.