在学习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(匹配失败不是异常)应用。
分析下流程:
- 当我们写入detail::has_no_destroy<T>::value 这段代码的时候,会触发sizeof(test<T>(0))的计算。
- 首先匹配模板 template <typename C> static char test(decltype(&C::no_destroy)); 如果匹配成功,那么test函数的返回类型也就为char,否则根据SFINAE原理,

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





