我有一个命令路由器,它将来自Web的JSON数据评估为C / C ++应用程序函数。我总是喜欢尝试新的东西,所以我想将路由器从C转换为C ++,因为我喜欢OOP。我想知道你是否可以使用std::map
将字符串映射到函数调用。
而不是这样做
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...);
答案 0 :(得分:0)
#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;
}