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()
;
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
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 executefunction541()
;
No, there is no easy way, because C++ does not have reflection . Function names only exist for the compiler. At run-time, there is no relationship between a function called function541
in your source code and the string "function541"
existing in memory while the program is being executed.
Each and any of such links must be established manually:
std::map<std::string, std::function<void()>> map;
// ...
map["function541"] = function541;
Of course, you can still automate such a task with code generation. Functions with mechanical names like this don't look like manually written C++ code anyway. That is, you can write a script in some other language that creates the C++ code to add the thousand functions to the map, perhaps as some kind of pre-build step.
Still, from a run-time point of view, there's no automation whatsoever.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.