Muduo里一个判断类里是否有一个函数的例子

 感受一下,在编译的时候,

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;
}

执行结果为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值