2

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?

4

2 に答える 2

7

静的レジストラー要素を追加できます。そのようなもの:

ベース.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; }

派生A.hpp:

#include "Base.hpp"

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

派生A.cpp:

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

が開始された後はいつでもmain()呼び出しBase::registry()て、派生クラスごとに 1 つの要素を含むマップへの参照を取得できます。

于 2012-05-14T19:44:00.440 に答える
1

それはできません。ほとんどの場合、実行時のクラス名がわからず、クラスのリストを取得できません。必要なすべてのクラスをインスタンス化したくない場合、唯一のオプションはリストを手動で作成することです。

于 2012-05-14T19:30:17.543 に答える