您可以定义一个类模板,该模板在T
您最终将要使用的子类上进行参数化,并且包含一个公共静态函数create()
,该函数与您的宏当前定义的完全相同
template<typename T>
struct Cocos2DSceneCreate
:
// each subclass of Cocos2DSceneCreate is automatically a subclass of cocos2d::CCScene
public cocos2d::CCScene
{
// exact same content as your macro
static cocos2d::CCScene* scene()
{
cocos2d::CCScene * scene = new cocos2d::CCScene;
scene->init();
T * layer = new T;
layer->init();
scene->addChild(layer);
layer->release();
scene->autorelease();
return scene;
}
};
然后你使用奇怪的重复模板模式(CRTP) 来混合所需的行为,方法是使用先前定义的模板派生每个子类,并将其自身作为参数(这就是“重复”这个词的来源)
class SomeNewSubClass
:
public Cocos2DSceneCreate<SomeNewSubClass>
{
// other stuff
};
请注意,SomeNewSubClass
它实际上是一个子类,cocos2d::CCScene
因为您Cocos2DSceneCreate
本身已经是一个子类。
另请注意,这个类模板解决方案比@Yuushi 的函数模板解决方案要复杂一些。额外的好处是,如果你有一个类模板比你有一个函数模板更容易为特定类型专门创建场景。如果您不需要专业化,请使用他的解决方案。