根据字符串,调用与字符串同名函数:
#include <map>
#include <string>
#include <iostream>
typedef void (*pFunc)();
std::map<std::string, pFunc> strFuncMap;
void func1()
{
printf("this is func1!\n");
}
void func2()
{
printf("this is func2!\n");
}
void buildMap()
{
strFuncMap["func1"] = &func1;
strFuncMap["func2"] = &func2;
}
void callFunc(const std::string& str)
{
if(strFuncMap.count(str))
(*strFuncMap[str])();
else
std::cout << "unsupported function str : " << str.c_str() << "\n" << std::endl;
}
int main()
{
buildMap();
//begin call func
callFunc("func1");
callFunc("func2");
callFunc("func3");
system("pause");
return 0;
}
输出结果:
this is func1!
this is func2!
unsupported function str : func3