g0lem – Programming and stuff

Programming and stuff

C++: Mapping functions to strings — October 30, 2018

C++: Mapping functions to strings

So, I wanted to build a console with which to execute functions with and the most obvious challenge would be to map a function to a string, so that when you input that string it will execute that said function. This feature is insanely easy to do in JavaScript:


var obj = {
    func: function(){
        console.log("FUNCTION CALLED");
    }
}

obj["func"]();

In C++, unsurprisingly, this is a bit more difficult.

First you would have to declare the data type:


typedef void strfunc_t();
typedef std::map CommandStringMap;

Then declare some functions you want to bind to strings:


void something(){
    std::cout<<"something called \n";
}

void somethingElse(){
    std::cout<<"somethingElse called \n";
}

You would also have to take into account the fact that the declaration of your “strfunc_t” function has to be exactly the same as the functions you are trying to bind to the map (something and somethingElse).

If you want to execute all functions in a string, you can use the following function:


void executeConsoleCommands(std::string str) {

            std::string delimiter = " ";
            size_t position;
            CommandStringMap commandStringMap = getCommandStringMap();
            if((position = str.find(delimiter)) != std::string::npos) {
                std::string token = str.substr(0, position);
                str = str.erase(0, position + delimiter.length());

                commandStringMap.find(token)->second();
                executeConsoleCommands(str);
            } else {

                commandStringMap.find(str)->second();
            }
        }
}

//then call this:

executeConsoleCommands("something somethingElse something");

at the end you are going to end up with something like this:

Download Gist