문제

I am working on cocos2dx game where for each subclass/scene I need to define something(macro) like this CREATECOCOS2DSCENE(CustomSceneNameScreen);` with following definition

 #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;}

How can I avoid specifying macro on each screen?

도움이 되었습니까?

해결책

Don't use a macro for this, use an inline template function:

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;
}

다른 팁

You could define a class template that is parameterized on the subclas T that you are eventually are going to use and that contains a public static function create() that does exactly what your macro currently defines

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;
    }
};

And then you use the Curiously Recurring Template Pattern (CRTP) to mixin the required behavior by deriving each subclass with the previously defined template with itself as parameter (this is where the word "recurring" comes from)

class SomeNewSubClass
:
    public Cocos2DSceneCreate<SomeNewSubClass>
{
    // other stuff
};

Note that SomeNewSubClass is in fact a subclass of cocos2d::CCScene because your Cocos2DSceneCreate is itself already a subclass.

Also note that this class template solution is a bit more complicated than the function template solution by @Yuushi. The added advantage is that it is easier to specialize the scene creation for specific types if you have a class template than if you have a function template. If you don't need to specialize, use his solution.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top