Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to pass a generic function name?

Tags:

c++

function

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?

like image 630
Tubbs Avatar asked Jun 03 '11 03:06

Tubbs


1 Answers

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)();
like image 76
James McNellis Avatar answered Oct 13 '22 19:10

James McNellis