-
Variable Function?
I was wondering if it is possible to call a variable function? Such as:
Code:
std::string Func = "CallThisFunction";
Func();
It would call CallThisFunction... I doubt it's possible, but if it is it will save me quite a bit of coding :)
- SirCrono6
-
One way is to set up a map, so long as all the called functions have the same prototype.
Something along the lines of
Code:
#include <map>
typedef void (*fntype)(void);
std::map<std::string,fntype> mapping;
// then set things up
mapping["CallThisFunction"] = func;
// then use is
mapping["CallThisFunction"] ();
-
...ahhh, I was wondering how to conjure up an associative array in C++. You can do something similar with two 'parallel arrays' if the STL is too frightening or is hidden behind a cloud of ignorance:
Code:
string names[3] = {"func1", "func2", "func3"};
void (*pfuncs[3])(void) = {func1, func2, func3};
string f = "func2";
for(int i = 0; i < (sizeof names/sizeof names[0]); i++)
{
if(names[i] == f)
pfuncs[i]();
}
A function pointer starts with the pointer:
*pfunc
and then you add parentheses around it:
(*pfunc)
and then you add the return type and the parameter type(s):
void (*pfunc)(void)
For an array of function pointers, you add in the array size:
void(*pfuncs[3])(void)
That also requires that the return types and parameter types are identical for all your functions.