Search code examples
c++templatesfactory-patterntemplate-meta-programming

Call function at program initialization time


So I'd like to be able to call a function at initialization time. It's a void function, but I want the side effects (updating a factory function table, in this case) to be in place by the time main() is called. Right now what I'm doing is just returning an int and initializing a static variable with it:

//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"

Is there a way I can call the static function without needing a static int?

I can post the complete source for the Factory classes, but what I'm more interested in is the compile-time or initialization-time function call


Solution

  • As was correctly pointed out by @interjay you are actually calling your function at initialization time (the time when static objects are initialized), not at compile time. AFAIK you won't be able to do this without having a static object. You might do this in the constructor of some static object though which might make the code look slightly simpler:

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