【发布时间】:2011-09-17 23:50:08
【问题描述】:
有谁知道让派生类自动实例化具有模板类型的静态变量的方法(这要么不需要派生类的编写者任何东西,要么强迫他调用这个静态方法以使派生类定义有效)。
这可能无法理解,我会尝试更好地定义它。
基本上,我有一个全局工厂类,其中包含一个名为 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";
}
【问题讨论】:
-
我要走的第一条路是让
Entity成为一个模板类,所以它知道派生类型。派生类型的问题要么必须是模板(因此是抽象的),要么永远不会用作基类。我还在 win32 包装器库中看到了用于此的宏。而且,这个问题有点相关 - stackoverflow.com/questions/138600/… -
Nm,它似乎被称为 CRTP,答案捕捉到了我所得到的 :)