Using CRTP (curiously recurring template pattern) you can provide a base class with knowledge of classes derived from it. It is not that hard to create an array that stores an instance of each class that derives from a base class (see example)
class Base{
public:
static std::vector<Base *> m_derivedInstances;
};
template <class Derived>
class CRTPBase : public Base {
public:
static bool m_temp;
static bool addInstance()
{
m_derivedInstances.push_back(new Derived);
return true;
}
};
template <class Derived>
CRTPBase<Derived>::m_temp = CRTPBase<Derived>::addInstance();
I was wondering if it was possible to create a Typelist (see http://www.research.ibm.com/designpatterns/pubs/ph-jun00.pdf) of all the types of derived classes. The problem is that every time the compiler sees a new class that derives from Base
it will need to append a new type to the list, but Typelists are immutable (it is possible to create a new list with the new type appended to it, but adding an element to a list is impossible as far as I know. In the end I would like to have something like this:
struct DerivedClassHolder {
typedef Loki::TL::MakeTypeList</*list all derived classes here*/>::Result DerivedTypes;
};
The ultimate goal is to be able to iterate over all the classes that derive from Base
.
It can be done, using a pseudo type-map. Here is some example code using boost::mpl. The explicit definition of "Implem" can be done with a macro in each corresponding implem header.