Best way to for C++ types to self register in a list?

You can execute something before main once if a instantiation of a template is made. The trick is to put a static data member into a class template, and reference that from outside. The side effect that static data member triggers can be used to call the register function:

template<typename D>
struct automatic_register {
private:
    struct exec_register {
        exec_register() {
            persistenceSystem::registerPersistableType(
                D::getPersister()
            );
        }
    };
    // will force instantiation of definition of static member
    template<exec_register&> struct ref_it { };

    static exec_register register_object;
    static ref_it<register_object> referrer;
};

template<typename D> typename automatic_register<D>::exec_register 
    automatic_register<D>::register_object;

Derive the class you want to be auto-registered from automatic_register<YourClass> . The register function will be called before main, when the declaration of referrer is instantiated (which happens when that class is derived from, which will implicitly instantiate that class from the template).

Having some test program (instead of the register function, a function do_it is called):

struct foo : automatic_register<foo> {    
    static void do_it() {
        std::cout << " doit "; 
    } 
}; 

int main() { 
    std::cout << " main "; 
}

Yields this output (as expected):

doit main

Leave a Comment