そのため、初期化時に関数を呼び出せるようにしたいと考えています。これはvoid関数ですが、呼び出されるまでに副作用(この場合はファクトリ関数テーブルの更新)が整っていることを望みますmain()
。今私がやっていることは、int を返し、それで静的変数を初期化することです:
//Factory inherits from FactoryBase
class FactoryBase
{
...
private:
static std::unordered_map<std::string, FactoryBase*> factoryTable;
public:
template<class C>
static int addClass(const std::string& name)
{
factoryTable[name] = new Factory<C>;
return 0;
}
};
...
int Foo::uselessStaticInt = FactoryBase::addClass<Foo>("foo");
//class Foo is now associated with the string "foo"
静的 int を必要とせずに静的関数を呼び出す方法はありますか?
Factory クラスの完全なソースを投稿できますが、もっと興味があるのは、コンパイル時または初期化時の関数呼び出しです。