有谁知道如何使派生类自动实例化具有模板类型的静态变量(这要么不需要派生类的编写者提供任何内容,要么强制他调用此静态方法以使派生类定义有效的)。
这可能是无法理解的,我会尝试更好地定义它。
基本上我有一个全局工厂类,带有一个名为 registerType 的模板化函数。对于从 Entity 派生的每个类,我需要使用派生类型的模板参数调用此函数。目前,我必须在某些 init 函数中手动执行此操作,这会导致对该函数的大量调用,这违背了我的模板原则。
所以我有这个:
class Factory
{
template <typename EntityType>
registerEntityType();
};
void someInitFunction()
{
/// All of these are derived from Entity
gFactory.registerEntityType<EntityType1>();
gFactory.registerEntityType<EntityType2>();
gFactory.registerEntityType<EntityType3>();
/// and so on
}
而我宁愿这样:
class Factory
{
template <typename EntityType>
registerEntityType();
};
class Entity // Abstract
{
/// This function should be called automatically with the derived
/// type as a parameter
SomeStaticConstructor<MDerivedType>()
{
gFactory.registerEntityType<MDerivedType>();
}
};
编辑:这是不起作用的静态重复模板代码:
这是我的基类,也是用于自动注册内容的类
template <typename DerivedType>
class Registrar
{
public:
Registrar();
void check();
};
template <typename Product, typename DerivedType>
class AbstractFactory: public AbstractFactoryBase<Product>
{
public:
AbstractFactory();
~AbstractFactory();
private:
static Registrar<DerivedType> registrar;
};
注册商的构造函数
template <typename DerivedType>
Registrar<DerivedType>::Registrar()
{
std::cout << DerivedType::name() << " initialisation" << std::endl;
g_AbstractFactories.registerFactoryType<DerivedType>(DerivedType::name());
}
以及派生类型
class CrateFactory : public AbstractFactory<Entity, CrateFactory>
{
public:
CrateFactory(FactoryLoader* loader);
virtual ~CrateFactory();
Entity* useFactory(FactoryParameters* parameters);
static std::string name()
{
return "CrateFactory";
}