C++ type_traits实现原理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25327609/article/details/89504332

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

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

猜你喜欢

转载自blog.csdn.net/qq_25327609/article/details/89504332