geoyar
geoyar

Reputation: 31

Enumerating derived classes in C++ executable

Suppose you have base class and several derived classes in your C++ app. You want to enumerate all classes derived from this base without instantiation the derived classes, say to present them to the user in the class name list box. Obviously, the needed information is somewhere in the app. How to retrieve it?

Upvotes: 2

Views: 1858

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

You can add a static registrar element. Something like so:

Base.hpp:

#include <string>
#include <typeindex>
#include <unordered_map>

using typemap = std::unordered_map<std::type_index, std::string>;

struct Base
{
    /* ... */
    static typemap & registry();
};

template <typename T> struct Registrar
{
    Registrar(std::string const & s) { Base::typemap()[typeid(T)] = s; }
};

Base.cpp:

#include "Base.hpp"
typemap & Base::registry() { static typemap impl; return impl; }

DerivedA.hpp:

#include "Base.hpp"

struct DerivedA : Base
{
    static Registrar<DerivedA> registrar;
    /* ... */
};

DerivedA.cpp:

#include "DerivedA.hpp"
Registrar<DerivedA> DerivedA::registrar("My First Class");

Now any time after main() has started you can call Base::registry() to get a reference to a map which contains one element per derived class.

Upvotes: 7

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

It can't be done. Most usually you don't known about class names in runtime and you can't get list of your classes. If you don't want to instantiate all needed classes, the only options is to build the list manually.

Upvotes: 1

Related Questions