参考
C++ 中通过函数名字的字符串调用函数
C++ 根据字符串 调用同名函数
#include <iostream>
#include <map>
#include <string>
using namespace std;
int use_foo1_1(int n)
{
return n;
}
int use_foo1_2(int n)
{
return n - 1;
}
int use_foo2_1(int n, int m)
{
return n + m;
}
int use_foo2_2(int n, int m)
{
return n * m;
}
void test1(void)
{
typedef int(*foo_type)(int); //函数类型由函数返回值类型和参数列表类型决定
typedef std::map<std::string, foo_type> foo_map_type;
foo_map_type map;
map["aaa"] = use_foo1_1;
map["bbb"] = use_foo1_2;
std::cout << (*map["aaa"])(10) << std::endl;
std::cout << (*map["bbb"])(10) << std::endl;
}
//由于 map的value部分只能接受一种类型
// use_foo1_1 和 use_foo2_1 不是同一种类型的函数
//所以 保存函数的指针 使用 void* 这样就能存储了,
// 但是通过函数指针调用函数的时候需要把 void* 转换成相对应的指针类型才行
//所以 一个map结点需要保存2个内容 函数指针和 转换函数的类型说明符号
void test2(void)
{
typedef int(*foo1_type)(int); //函数类型由函数返回值类型和参数列表类型决定
typedef int(*foo2_type)(int, int);
typedef std::map<std::string, std::pair<void*, int> > foo_map_type;
foo_map_type map;
map["aaa"] = std::pair<void*, int>(use_foo1_1, 1);
map["bbb"] = std::pair<void*, int>(use_foo2_1, 2);
if (map["aaa"].second == 1)
{
std::cout << (*reinterpret_cast<foo1_type>(map["aaa"].first))(10) << std::endl;
}
if (map["aaa"].second == 2)
{
std::cout << (*reinterpret_cast<foo2_type>(map["aaa"].first))(10, 20) << std::endl;
}
if (map["bbb"].second == 1)
{
std::cout << (*reinterpret_cast<foo1_type>(map["bbb"].first))(10) << std::endl;
}
if (map["bbb"].second == 2)
{
std::cout << (*reinterpret_cast<foo2_type>(map["bbb"].first))(10, 20) << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
test2();
return 0;
}