在程序初始化时调用函数

时间:2012-06-17 19:31:59

标签: c++ templates factory-pattern template-meta-programming

所以我希望能够在初始化时调用函数。这是一个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类的完整源代码,但我更感兴趣的是编译时或初始化时函数调用

2 个答案:

答案 0 :(得分:1)

正如@interjay正确指出的那样,你实际上是在初始化时(初始化静态对象的时候)调用你的函数,而不是在编译时。如果没有静态对象,AFAIK将无法执行此操作。您可以在某个静态对象的构造函数中执行此操作,但这可能会使代码看起来更简单:

ClassRegister<Foo> fooRegister("foo"); // Call FactoryBase::addClass<Foo>("foo")
                                       // in the constructor of ClassRegister<Foo>

答案 1 :(得分:0)

我经常使用辅助registrator类,以及一个全局实例:

标题文件FactoryBase.hpp

template <typename T> struct Registrator
{
    explicit Registrator(char const * s)
    {
        FactoryBase<T>::addClass(s);
    }
};

(如果您愿意,这可以是FactoryBase中的公共嵌套类。)

翻译单位:

#include <FactoryBase.hpp>
#include <Foo.hpp>

namespace
{
    Registrator<Foo> fooRegistrator("foo");
}