0

I have a command router that takes evaluates JSON data from the web into C/C++ application functions. I always like to try new things so I wanted to convert the router from C to C++ because I enjoy OOP. I was wondering if you can use std::map to map strings to function calls.

Instead of doing this

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
    }
}

Can I instead use map to avoid all that?

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

// now simply..
CmdMap[jsonObject.cmd](...arguments...);
  • 1
    Look into `std::function`. – Jesper Juhl Feb 01 '17 at 21:15
  • Yes, you can do that. That's exactly the sort of thing maps are for. Of course your syntax is all wrong, but you'll figure it out with some research and patience. It looks like you may need [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1). Remember, although they look similar, C++ is nothing like C# or Java, and it's so much more than C, so forget what you know about those languages. – Rob K Feb 01 '17 at 21:35

1 Answers1

0

yes, something like this:

#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;
}
Wagner Patriota
  • 5,494
  • 26
  • 49