I have 300+ classes. They are related in some ways.
For simplicity, all relation are 1:1.
Here is a sample diagram.
(In real case, there are aroun
My suggestion:
class Base
{
public:
virtual ~Base();
// Add "child" to the list of children of "this"
// Add "this" to the list of parents of "child"
void addChild(Base* child);
// Remove "child" from the list of children of "this"
// Remove "this" from the list of parents of "child"
void removeChild(Base* child);
std::vector & getParents();
std::vector const& getParents() const;
std::vector & getChildren();
std::vector const& getChildren() const;
private:
std::vector parents_;
std::vector chilren_;
};
Now you can implement higher level functions. E.g.
// Call function fun() for each child of type T of object b.
template
void forEachChild(Base& b, void (*fun)(T&))
{
for ( auto child, b.getChildren() )
{
T* ptr = dynamic_cast(child);
if ( ptr )
{
fun(*ptr);
}
}
}
To query the unique egg
from a hen
, you could use a generic function template.
template
T* getUniqueChild(Base& b)
{
T* child = nullptr;
for ( auto child, b.getChildren() )
{
T* ptr = dynamic_cast(child);
if ( ptr )
{
if ( child )
{
// Found at least two.
// Print a message, if necessary.
return NULL;
}
child = ptr;
}
}
return child;
}
and then use it as:
hen* henptr = ;
egg* eggptr = getUniqueChild(*henptr);