感受一下,在编译的时候,
1、模板函数不需要具体的实现
2、从sizeof(test<T>(0))的写法可以看出来,编译器想要分析函数的返回值,并不需要具体的函数实现,test<T>(0)并不是真正传给函数0这个值,只是让其“挑选”正确的函数。
3、模板函数的重载,看来是...那个优先级最低
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
//判断类里是否有no_destroy这个函数
#include <iostream>
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
template <typename T>
static void init(T t)
{
T* value_ = new T();
if(value_!=nullptr)
{}
if (!detail::has_no_destroy<T>::value)
{
std::cout << "× 没有 no_destroy 这个函数" << std::endl;
//std::cout << "is ok" << t << std::endl;
//::atexit(destroy);
}
else
{
std::cout << "√ 有 no_destroy 这个函数" << std::endl;
}
}
struct XXX
{
static bool no_destroy()
{
return true;
}
};
int main()
{
//decltype(&XXX::no_destroy) x = 0;
XXX o;
init<XXX>(o);
int num = 200;
init<int>(num);
return 0;
}
运行结果就是:
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
//试试函数模板的重载。以及...的优先级(最低)
#include <iostream>
struct XXX
{
static bool no_destroy()
{
return true;
}
};
template <typename C> static char test(decltype(&C::no_destroy))
{
std::cout << "has no_destroy" << std::endl;
return '0';
}
template <typename C> static int32_t test(...)
{
std::cout << "does not have no_destroy" << std::endl;
return 1;
}
int main()
{
test<int>(0);
test<XXX>(0);
return 0;
}
执行结果为: