[英]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.