在学习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_destro