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
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;
}