[英]How to define generic templated create function for subclass
我正在研究cocos2dx游戏,我需要为每个子类/场景定义一些东西(宏),如CREATECOCOS2DSCENE(CustomSceneNameScreen);`具有以下定义
#define CREATECOCOS2DSCENE(T)\
\
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;}
如何避免在每个屏幕上指定宏?
不要为此使用宏,使用内联模板函数:
template <typename T>
inline 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;
}
您可以定义一个类模板,该类模板在您最终将要使用的子类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) 混合所需的行为,方法是将每个子类与先前定义的模板一起导出,并将其自身作为参数(这是单词“recurring”来自的地方)
class SomeNewSubClass
:
public Cocos2DSceneCreate<SomeNewSubClass>
{
// other stuff
};
请注意, SomeNewSubClass
实际上是cocos2d::CCScene
的子类,因为您的Cocos2DSceneCreate
本身已经是子类。
另请注意,此类模板解决方案比@Yuushi的函数模板解决方案复杂一些。 另外一个优点是,如果您拥有类模板,则比使用功能模板更容易专门为特定类型创建场景。 如果您不需要专业化,请使用他的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.