benben wrote:
Gary Wessle wrote:
Hi
is there a way to convert a string to a function name and fire it. like
void his_fun(){
cout << "his is here" << endl;
}
vector<stringvec;
vec.push_back("his");
vec.push_back("me");
for(i=0; i<vec.size(); i++)
string var = vec[i] + _fun;
fire(var); and it will fire the routine "his_fun?
is so, how?
#include <string>
#include <map>
#include <iostream>
typedef void (*func_ptr)(void);
std::map<std::string, func_ptrfunctions;
void fun1()
{
std::cout << "fun1\n";
}
void fun2()
{
std::cout << "fun2\n";
}
int main()
{
functions["fun1"] = &fun1;
functions["fun2"] = &fun2;
std::string name;
std::cin >name;
functions[name](); // invoke
}
This is exceedingly dangerous. The [] lookup operation is non-const
because it does an insert cum default intialization if the key is not
found, and since the result (the function pointer) is immediately
dereferenced and invoked, this would mean dereferencing a null pointer,
which, as you know, is bad bad bad. The safe alternative is to use
map::find for lookups (unless you're absolutely sure that the string is
one of your keys, but even then, I'd prefer to err on the side of
caution to prevent future changes from creating problems).
Cheers! --M