I was wondering if it is possible to call a variable function? Such as:
It would call CallThisFunction... I doubt it's possible, but if it is it will save me quite a bit of codingCode:std::string Func = "CallThisFunction"; Func();
- SirCrono6
I was wondering if it is possible to call a variable function? Such as:
It would call CallThisFunction... I doubt it's possible, but if it is it will save me quite a bit of codingCode:std::string Func = "CallThisFunction"; Func();
- SirCrono6
From C to shining C++!
Great graphics, sounds, algorithms, AI, pathfinding, visual effects, cutscenes, etc., etc. do NOT make a good game.
- Bubba
IDE and Compiler - Code::Blocks with MinGW
Operating System - Windows XP Professional x64 Edition
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"] ();
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
...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:
A function pointer starts with the pointer: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](); }
*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.
Last edited by 7stud; 02-24-2005 at 03:08 AM.