Map Of functions c++

2019-03-25 06:41发布

I have made a map of functions. all these functions are void and receive single string parameter.

code:

void f1(string params){...}
void f2(string params){...}
void f3(string params){...}

map<string , void*> funcMap;

funcMap["f1"] =(void*)&f1;
funcMap["f2"] =(void*)&f2;
funcMap["f3"] =(void*)&f3;

how do i call a function? I tried the next code, but id doesn't work:

void (*func)(string) =  &funcMap[commandType];
func(commandParam);

I get this error message:

Server.cpp:160:46: error: cannot convert ‘void**’ to ‘void (*)(std::string) {aka void (*)(std::basic_string<char>)}’ in initialization

3条回答
欢心
2楼-- · 2019-03-25 07:06

Why not just have those as separate classes.

Then have the methods as virtual.

You can then have a map between the string and the base class.

i.e.

class Someoperation
{
    virtual void Doit() = 0;
};

map<string, Someopertion> ops;

Then

class MyOp : public Someoperation
{
   void Doit() { /* Some code here */}
};

Just add objects

ops["Hello"] = MyOp();

then call it

ops["Hello"].Doit();
查看更多
虎瘦雄心在
3楼-- · 2019-03-25 07:23

&funcMap[commandType]

Just drop the &. Your compile error was useful here. It had a void** on the right which is because you took the address of a function pointer. You don't want two levels of indirection there.

查看更多
Deceive 欺骗
4楼-- · 2019-03-25 07:28
typedef void (*pfunc)(string);

map<string, pfunc> funcMap; 
funcMap["f1"] = f1; //and so forth

And then call:

pfunc f = funcMap[commandType];
(*f)(commandParam);   

In general, why throw away type safety? If it's a map of function pointers, declare it to be one.

查看更多
登录 后发表回答