Please consider the following boilerplate class fragment:
class ObjectA : public BaseObject
{
DerivedMemberA a, a2, a3;
DerivedMemberB b;
DerivedMemberC c;
// ...
};
The DerivedMember* types are derived from a common BaseMember class, and ObjectA (and similar ObjectB, ObjectC…) would be derived from BaseObject.
Now I’d like to implement an iterator which would be in public BaseObject interface, and which would iterate over references to members of the derived classes (as BaseMember&).
In other words, the use would be like:
BaseObject& b = someObject;
for (BaseObject::iterator it = b.begin(); it != b.end(); ++it)
{
BaseMember& m = *it;
// ...
}
which called on ObjectA would iterate over a, a2…
What is the best way to solve this? Preferably avoiding subclassing the iterator as well. Is there any ready iterator class or template which could be reused there?
I was thinking of implementing a virtual member function which would take numerical ‘index’ of a variable and using a switch to return the appropriate reference; then calling that member from index-keeping iterator.
C++ doesn’t have any concept of introspection, so there’s absolutely no way for the base class to know what members are defined in the derived class.
The best you can do is create a virtual function in each derived class that iterates through its own members.