LoginSignup
5
5

More than 5 years have passed since last update.

メンバ関数ポインタを配列で管理して読みやすくする

Posted at

cocos2d-xだとメソッドを呼び出したSenderのタグで処理を分けたりすることも多いかもしれません。しかし、多くなった時の処理が大変になります


enum struct ButtonType
{
    Sound,
    Notification
}


void onTouchButton(Ref* pSender)
{
    Node* node = dynamic_cast<Node*>(pSender);
    int tag = node->getTag();
    ButtonType type = static_cast<ButtonType>(tag);

    if(type == Sound)
    {
        sound();
    }
     else if(type==Notification)
    {
        notify();
    }
}



これだと、if文がどんどん増えて冗長になりますよね。なので、そもそもよぶメソッドを関数ポインタにしてstatic_castをほどこしてよぶようにします。

Menuのenum

enum struct Menu
{
    HELP,
    PLAY,
    TITLE,
    RANKING
};


void (*fptrs[])() =
{
    &showHelp,
    &showPlay,
    &showTitle,
    &showRanking,
};

// 使い方
(this->*fptrs[static_cast<int>(Menu::HELP)])();


5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5