转自:http://bbs.csdn.net/topics/290032347
概括:将成员函数指针名和同名的string类型的变量名进行绑定,插入到map中。
在使用时就可以通过找到string类型的变量名来使用同名的函数
#include "iostream"
#include "string"
#include "map"
using namespace std;
class test
{
public :
void fun1() { cout<<"call test::fun1"<<endl; }
void fun2() { cout<<"call test::fun2"<<endl; }
void fun3() { cout<<"call test::fun3"<<endl; }
test()
{
m_mapFun["test::fun1"] = &test::fun1;
m_mapFun["test::fun2"] = &test::fun2;
m_mapFun["test::fun3"] = &test::fun3;
}
void call(string strfun)
{
if (m_mapFun.find(strfun) == m_mapFun.end())
cout<<"no function : "<<strfun<<endl;
else
(this->*m_mapFun[strfun])();
}
protected :
typedef void (test::*mfun)();
map<string, mfun> m_mapFun;
};
int main()
{
test t;
t.call("test::fun1");
t.call("test::fun2");
t.call("test::fun3");
t.call("test::fun4");
return 0;
}
-----------------
结果:
call test::fun1
call test::fun2
call test::fun3
no function : test::fun4