Here's a fairly normal encapsulation of an STL container which allows the user of Cfoo to iterate the container without allowing changes to the innards.
#include <vector>
class Cfoo
{
public:
class Cbar
{
/* contents of Cbar */
};
typedef std::vector<Cbar> TbarVector;
typedef TbarVector::const_iterator const_iterator;
public:
const_iterator begin() const { return( barVector_.begin() ); }
const_iterator end() const { return( barVector_.end() ); }
private:
TbarVector barVector_;
};
So far, so good. We can iterate the container like this:
Cfoo myFoo;
for (Cfoo::const_iterator it = myFoo.begin(); it != myFoo.end(); ++it)
{
it->DoSomething();
}
Now I want to replace the std::vector with say a nested std::vector:
public:
typedef std::vector<Cbar> TbarVectorInner;
typedef std::vector<TbarVectorInner> TbarVectorOuter;
private:
TbarVectorOuter barContainer_;
But I want to be able to iterate over all the instances of Cbar in the same way as before, exposing a const_iterator, and a begin()const and an end()const method.
I'm not clear how to do that, though I suspect it involves writing a custom iterator. Any thoughts?
TbarVector
should be private, it tells to the outside world things that are not relevant to it and is prone to misuse. – Sebastian Mach