I am building a program in c++ where the user can set a function to be called when user defined conditions are reached. I am only a little experienced with c++.
I know how to do this in python. You would simply define functions and put the names of said functions into a structure (I always used a dictionary). When you go to use the function, you would make a call similar to:
methods = { "foo" : foo, "bar" : bar }
choice = input("foo or bar? ")
methods[choice]()
Any ideas on how to pull this off in c++ without having to hardcode everything?
Your Python code actually translates to C++ pretty much directly:
Python’s dictionary is similar to C++’s
map. They’re both associative containers, mapping a value from one type to a value of another (in our case, string to function).In C++, functions aren’t quite first-class citizens, so you can’t store a function in a map, but you can store a pointer to a function. Hence the map definition gets a bit hairy, because we have to specify that the value type is a “pointer to a function which takes no arguments and returns void”.
On a side note, it is assumed that all your functions have the same signature. We can’t store both functions that return void and functions that return an int in the same map without some additional trickery.