简体   繁体   中英

C++ template for classes with static method

I'm currently programming a game using cocos2dx engine and I have a level manager that keeps track of the current level and the scene that needs to be loaded. I want to avoid long if statements, such as this:

Scene* scene;
if (level == 1)
{
      scene = Game_Scene1::createScene();
}
else if (level == 2)
{
      scene = Game_Scene2::createScene();
}
else if (level == 3)
{
      scene = Game_Scene3::createScene();
}
(...)
else if (level == 10)
{
      scene = Game_Scene10::createScene();
}

Director::getInstance()->replaceScene(TransitionFade::create(0.5, scene, Color3B(0,0,0)));

The screateScene() method is a static method

static cocos2d::Scene* createScene();

What could I do to "remove" the if statement? So it would look something like this:

Scene* scene = getScene(level, sceneClass::createScene());

and it would take the correct class (that is: Game_Scene1 , Game_Scene2 etc.)

Is there a nice solution for such problem? The title says template but I'm not really sure if the solution for this is a template.

One simple solution would be to used a table of pointer functions.

You could declare your table as

typedef cocos2d::Scene *(*PtfCreateScene)();
PtfCreateScene tab[10];

tab[0] = Game_Scene1::create_scene;
tab[1] = Game_Scene2::create_scene; ... 

Using this solution you can then call the associated create_scene function using level as an index. Thus avoiding the if branchings .

scene = tab[level - 1]();

You will have to check the correctness of the index to avoid out of memory access.

Hope I answered your question. Don't hesitate to ask if you need more explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM