2017-02-01 2 views
0

WebからJSONデータをC/C++アプリケーション関数に評価するコマンドルーターがあります。私はいつも新しいものを試してみたいので、ルータをCからC++に変換したかったので、OOPを楽しんでいます。 std::mapを使用して文字列を関数呼び出しにマップできるかどうか疑問に思っていました。代わりに私が代わりにすべてのことを避けるために、マップを使用することができ、このC++のマッピング関数

enum myCommands { 
    cmdGetUserName, 
    cmdGetUserId 
}; 
struct cmdRoutes cmdList[] = { 
    {"getUserName", cmdGetUserName}, 
    {"getUserId", cmdGetUserId} 
} 
void processCmd(json jsonObject) 
{ 
    int cmd = getCmd(jsonObject.cmd, cmdList); 
    switch(cmd){ 
     case cmdGetUserName: 
     case cmdGetUserId: 
     ...etc 
    } 
} 

を行う

std:map<string, AppStatus> CmdMap; 
CmdMap["getUserName"] = MyClass.GetUserName; 

// now simply.. 
CmdMap[jsonObject.cmd](...arguments...); 
+1

ルック。 –

+0

はい、そうすることができます。それはちょうど地図がある種類のものです。もちろん構文はすべて間違っていますが、あなたはいくつかの研究と忍耐でそれを理解します。あなたは[良いC++の本](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1)が必要なようです。似ていますが、C++はC#やJavaのようなものではないことを覚えておいてください。 –

答えて

0

はい、このような何か: `のstd :: function`に

#include <iostream> 
#include <map> 

using namespace std; 

// change the signature int(int) to whatever you have in your functions, or course 
typedef std::function<int(int)> FunctionType; 

int function1(int arg) 
{ 
    return arg + 1; 
} 

int function2(int arg) 
{ 
    return arg + 2; 
} 

int main(int argc, char* argv[]) 
{ 
    map<string, FunctionType> functionList; 

    functionList["one"] = function1; 
    functionList["two"] = function2; 

    cout << functionList["one"](1) << endl; 
    cout << functionList["two"](2) << endl; 

    return 0; 
}