Automatic static invocation of derived types

前端 未结 3 1537
旧巷少年郎
旧巷少年郎 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:27

    I'd recommend a CTRP-backed approach:

    // Entity.h
    class EntityBase
    { // abstract
    };
    
    template
    class Entity
      : public EntityBase
    { // also abstract thanks to the base
      static char _enforce_registration; // will be instantiated upon program start
    };
    
    // your actual types in other headers
    class EntityType1
      : public Entity
    { // automatic registration thanks to the _enforce_registration of the base
      // ...
    };
    
    // Entity.cpp
    #include "Entity.h"
    
    template
    char RegisterType(){
      GetGlobalFactory().registerEntityType();
      return 0; // doesn't matter, never used.
    }
    
    template
    char Entity::_enforce_registration = RegisterType();
    

    Though, as seen, you now need to get your factory through a GetGlobalFactory function, which lazy initializes the factory to ensure that it has been initialized before the enforced registration happens:

    Factory& GetGlobalFactory(){
      static Factory _factory;
      return _factory;
    }
    

提交回复
热议问题