C++字符串转函数名

参考
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;
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值