Automatic static invocation of derived types

前端 未结 3 1541
旧巷少年郎
旧巷少年郎 2021-02-02 18:03

Does anyone know of a way to make derived classes automatically instantiate a static variable with a template type (this either has to require nothing from the writer of the der

3条回答
  •  春和景丽
    2021-02-02 18:39

    If anyone is still interested, I figured it out. Static template member variables are not automatically instantiated unless they are used. I needed it to be instantiated before the constructor was called, so I couldn't make it a static local. The solution is to make it a static template member variable, and then use it (just call an empty function on it if you want) in a member function (I use the constructor). This forces the compiler to instantiate the static for every template parameter ever declared, because the instantiated constructor code uses it, for example:

    My registry class, with its blank function for calling

    template 
    class Registrar
    {
        public:
            Registrar();
            void check(){}
    };
    

    My class I want registered.

    template 
    class AbstractFactory: public AbstractFactoryBase
    {
        public:
            AbstractFactory();
            ~AbstractFactory();
        private:
            static Registrar registrar;
    };
    

    The registrar's constructor

    template 
    Registrar::Registrar()
    {
        std::cout << DerivedType::name() << " initialisation" << std::endl;
        g_AbstractFactories.registerFactoryType(DerivedType::name());
    }
    

    And my classes constructor

    template 
    AbstractFactory::AbstractFactory()
    {
        registrar.check();
    }
    

提交回复
热议问题