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?
You can use a map of function pointers:
void foo() { }
void bar() { }
typedef void (*FunctionPtr)();
typedef std::map<std::string, FunctionPtr> FunctionMap;
FunctionMap functions;
functions.insert(std::make_pair("foo", &foo));
functions.insert(std::make_pair("bar", &bar));
std::string method = get_method_however_you_want();
FunctionMap::const_iterator it(functions.find(method));
if (it != functions.end() && it->second)
(it->second)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With