C ++ How to create a map that takes a string and returns a function

I was wondering if there is a way to make the map (in C ++) return func. This is my code now and it does not work, I get a compiler error.

#include <map> #include <iostream> #include <string> using namespace std; map<string, void()> commands; void method() { cout << "IT WORKED!"; } void Program::Run() { commands["a"](); } Program::Program() { commands["a"] = method; Run(); } 

Any advice would be awesome! Thank you in advance.

+4
source share
2 answers

You cannot save a function on the map โ€” just a pointer to a function. With some other minor details cleared, you will get something like this:

 #include <map> #include <iostream> #include <string> std::map<std::string, void(*)()> commands; void method() { std::cout << "IT WORKED!"; } void Run() { commands["a"](); } int main(){ commands["a"] = method; Run(); } 

At least with g ++ 4.7.1, this prints IT WORKED! as you apparently wanted / expected.

+4
source

Again typedef is your friend.

 typedef void (*func)(); map<string, func> commands; 
+2
source

Source: https://habr.com/ru/post/1441435/


All Articles