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.