基于c++11新特性的safe_call wapper

今天调试项目,进入了一个公司写的源代码去看,其中写了一个wapper层。核心代码如下:

std::map<std::thread::id, std::exception> exceptions;
std::map<std::thread::id, bool> exceptions_read;

template<typename class_type, typename ret_type, typename ...arg_type>
inline ret_type safe_call(class_type* instance, ret_type(class_type::* method)(arg_type...), arg_type... args) {
	try {
		return (instance->*method)(std::forward<arg_type>(args)...);
	}
	catch (std::exception ex)
	{
		auto thread_id = std::this_thread::get_id();
		exceptions_read[thread_id] = false;
		exceptions[thread_id] = ex;
	}
	return ret_type();
}

其中safe_call执行的内容是,把类型为class_type的对象的一个返回值为ret_type,参数类型为arg_type的函数进行安全调用。若成功则返回ret_type,失败则把异常保存在一个map李,key值为调用他的线程号。

其中使用了不少c++11的新特性

  • …arg_type 作为模板函数的可变参数列表,允许调用的函数拥有若干个类型。
  • std::forward<arg_type>(args)… 实现完美转发,避免多次调用构造函数。
  • std::this_thread::get_id(); this_thread是c++11提供的的一个命名空间,其下有get_id();sleep_for();sleep_until();yield() 四个函数。
  • thread类下提供了id的类型。此类型是this_thread::get_id()或者thread::get_id()的返回值,该段代码中将其作为map的key。
  • 这段代码完成的功能是统一处理异常,使程序在想要终止的地方终止,而不是在异常发生的时候
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值