Re: How to call a function just using a string?
On Dec 6, 7:11 am, moxemer...@gmail.com wrote:
Dear Terminator,
I find your code to be quite enthralling, however, I do not understand
the bulk of it. =(
Could you comment out your lines so that I understand what is going
on.
We need a global mapper object that maps every desired function to a
string , but global objects couse some troubles in initialization ,so
we need some tricks.
I wrote:
#include <map>
#include <string>
typedef std::map<std::string,void(*)(void)> FuncMapTypeBase;
// define a class in order to initialize a static object.
struct FuncMapType :
/*
inherit from the type that is intended to be used for the static
object:
*/
FuncMapTypeBase
{
/*
define the initializer code for the static object:
*/
FuncMapType(){
(*this)["fun1"]=&fun1;
(*this)["fun2"]=&fun2;
(*this)["fun3"]=&fun3;
}
};
/*
define a static-object-wrapper to make sure the static object is
well constructed before first use:
*/
const FuncMapType &funxns(){
/*
map every function to a string so that you can find it via the
string:
*/
static FuncMapType funcs;
return funcs;
};
//just what the OP wanted:
void funcall(const std::string& str){
// call function pointer 'key'ed by 'str':
(*(funcxns()[str]))();
};
Is it undersandable now?
regards,
FM.