C++ type_traits实现原理

以 is_void 为例分析,源代码选择vs2017库文件
#include<iostream>
#include<type_traits>
int main()
{
	std::cout << std::is_void<void>::value;// 1
	std::cout << std::is_void<int>::value; // 0	
	return 0;
}

查看is_void源码为:

template<class _Ty>
	struct is_void
		: false_type
	{	// determine whether _Ty is void
	};

#define _IS_VOID(CV_OPT) \
template<> \
	struct is_void<CV_OPT void> \
		: true_type \
	{	/* determine whether _Ty is void */ \
	};

_CLASS_DEFINE_CV(_IS_VOID)
#undef _IS_VOID

即为:特化模板参数,void是继承自true_type,否则继承自false_type,有点思路了,但是这两者是什么呢?

// ALIAS TEMPLATE bool_constant
template<bool _Val>
using bool_constant = integral_constant<bool, _Val>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;

继续刨根问底到 integral_constant

template<class _Ty,_Ty _Val>
struct integral_constant
{
	// convenient template for integral constant types
	static constexpr _Ty value = _Val;
	
	using value_type = _Ty;
	using type = integral_constant;
	
	constexpr operator value_type() const noexcept
	{	// return stored value
		return (value);
	}
	
	_NODISCARD constexpr value_type operator()() const noexcept
	{	// return stored value
		return (value);
	}
};

这里面 static constexpr _Ty value = _Val; 显而易见的定义了一个静态的bool类型变量,这时候再看到,恍然大悟。

template<bool _Val>
using bool_constant = integral_constant<bool, _Val>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;

总之,就是使用模板编程和继承的技巧,在编译器实现了这样的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值