techy techy - 1 month ago 6
C++ Question

C++ call function with string as parameter

Lets say I have several functions like

function1()
,
function2()
, .....,
function1000()

and I am getting a string in a function lets say
call_function(string function_name)
.

Now I need to execute function based on
function_name
.

I searched for solutions and found I can use maps.

Is there any easy way to create a map for lets say 1000
keys(string type)
and respective functions ?

eg:
call_function(function541)
then it should execute
function541()
;

Answer

You can use map to function pointers for this stuff

void func1(const char *args)
{
     //....
}

void func2(const char *args)
{
     //....
}

typedef void (*function) (const char *args);

//......

std::map<std::string, function> func_map;

func_map.insert(std::pair<std::string, function>("func1", func1));
func_map.insert(std::pair<std::string, function>("func2", func2));

func_map["func1"]("arg1 arg2 arg3"); // Here is the func1 call