STL源码分析——type_traits

本文深入探讨C++11中的type_traits库,详细解释如何利用type_traits进行编译期计算、判断和类型转换。通过具体实例展示了is_const和integral_constant的实现,帮助读者理解元编程在C++中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

type_traits

type_traits是C++11提供的模板元基础库。
type_traits可实现在编译期计算、判断、转换、查询等等功能。
type_traits提供了编译期的true和false。

// type_traits中源码
//is_const的实现
//以下为了和实际源代码区分,全部加了my
template<typename _Tp>
struct my_is_const
	: public my_false_type
{ };    // 泛化版本

template<typename _Tp>
struct my_is_const<_Tp const>
	: public my_true_type
{ };    // 偏特化版本

// integral_constant
template<typename _Tp, _Tp __v>
struct my_integral_constant
{
	static constexpr _Tp                  value = __v;//静态数据成员
	typedef _Tp                           value_type;
	typedef my_integral_constant<_Tp, __v>   type;

};


typedef my_integral_constant<bool, true>     my_true_type;

typedef my_integral_constant<bool, false>    my_false_type;

int main()
{
	cout << my_is_const<int>::value << endl;//0
	cout << is_const<int>::value << endl;//0
	cout << my_is_const<const int>::value << endl;//1
	cout << is_const<const int>::value << endl;//1
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值