1

我正在开发 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;}

如何避免在每个屏幕上指定宏?

4

2 回答 2

2

不要为此使用宏,使用内联模板函数:

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;
}
于 2013-04-18T07:35:59.983 回答
1

您可以定义一个类模板,该模板在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 的函数模板解决方案要复杂一些。额外的好处是,如果你有一个类模板比你有一个函数模板更容易为特定类型专门创建场景。如果您不需要专业化,请使用他的解决方案。

于 2013-04-18T07:35:05.380 回答