Skip to content

C++ Runtime Types: Find All Classes Derived From a Base Class (2)

Working on a way to find all the derived classes of a base class: part 1 is here, discussing the motivation and frame of the problem.

StackOverflow gives a pointer to meatspace (a blog), where he’s got a solution involving factory methods and a single macro per class.

class Base;

typedef Base* (*base_creator)(void);

class BaseRegistry {
        std::vector m_bases;

class BaseRegistration {

#define AUTO_REGISTER_BASE(base) \
    BaseRegistration _base_registration_ ## base(&base_factory);

It’s functional: you can walk through all the registered base classes and create an instance of each.   The example doesn’t provide a way to reverse the index (to go from a derived class its position in the factory method table) but that would be easy to add.

Another minor complaint is that this example hardcodes the identity of the base class. If you wanted to have two distinct hierarchies of derived classes, you’d need to change a few things, not just a single template argument.

Another minor complaint — so minor that I hesitate to mention it — is that each of the derived classes is assumed to have its own implementation file. That’s fine for a situation where the derived classes are doing some actual work, but my error classes are very lightweight and won’t have their own implementation files. This is a purely aesthetic objection.

The main drawback that I see is maintainability: it seems too easy to fall through the cracks. I can declare a class derived from type CBase and if I forget to put the AUTO_REGISTER_BASE(CDerived) macro in an implementation file, the class doesn’t get registered and therefore can’t be enumerated. In this framework, there’s no way to enforce the rule that each derived class must be registered.