muduo 中 has_no_destroy 模板

本文深入剖析了muduo库中has_no_destroy模板的实现,利用SFINAE原则在编译时检查类型T是否包含no_destroy方法。通过sizeof运算触发模板函数匹配,根据返回类型大小推断特征。了解这一技巧有助于掌握C++模板编程的精髓,并能应用于静态检查和避免运行时错误。
摘要由CSDN通过智能技术生成

在学习muduo源码中,单例模式实现的源码中有这么一段

namespace detail
{
// This doesn't detect inherited member functions!
// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
template<typename T>
struct has_no_destroy
{
  template <typename C> static char test(decltype(&C::no_destroy));
  template <typename C> static int32_t test(...);
  const static bool value = sizeof(test<T>(0)) == 1;
};
}  // namespace detail




 static void init()
  {
    value_ = new T();
    if (!detail::has_no_destroy<T>::value)
    {
      ::atexit(destroy);
    }
  }

has_no_destroy 实现了在编译期间判断泛型T中是否存在no_destroy方法。这个实现的原理追究起来也就是对模板编程中的SFINAE(匹配失败不是异常)应用。

分析下流程:

  1. 当我们写入detail::has_no_destroy<T>::value 这段代码的时候,会触发sizeof(test<T>(0))的计算。
  2. 首先匹配模板 template <typename C> static char test(decltype(&C::no_destro
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值