c++ std::conditional详解

std::conditionalC++11引入的类模板,表示的是一种编译期的分支逻辑,我们来看看它的源码吧,其实非常的简单。

// STRUCT TEMPLATE conditional
template <bool _Test, class _Ty1, class _Ty2>
struct conditional { // Choose _Ty1 if _Test is true, and _Ty2 otherwise
    using type = _Ty1;
};

template <class _Ty1, class _Ty2>
struct conditional<false, _Ty1, _Ty2> {
    using type = _Ty2;
};

template <bool _Test, class _Ty1, class _Ty2>
using conditional_t = typename conditional<_Test, _Ty1, _Ty2>::type;

从以上可以看到,std::conditional 包含一个泛化和特化的版本,在结构体里面用type来表示类型模板参数的类型,当第一个非类型模板参数的值为true时,type的类型为第一个类型模板参数的类型,为false时为第二个类型模板参数的值。

#include<iostream>
#include <string>
using namespace std;
int main(void)
{
	std::conditional<false, int, float>::type var;
	std::cout << typeid(decltype(var)).name() << std::endl;
	std::conditional<true, int, float>::type var1;
	std::cout << typeid(decltype(var1)).name() << std::endl;
}

在这里插入图片描述
再来看一个复杂点的例子,逻辑上类似与if-else

#include<iostream>
#include <string>
using namespace std;
int main(void)
{
	constexpr int j = 135; //假设给进去35
	std::conditional<
		(j > 100), double,  //值>100,var是double,
		std::conditional<
		(j > 80), float, //值在80-100之间,那么var是float类型。
		std::conditional<
		(j > 40), int,  //值在40-80之间,那么var是int类型。
		char       //值不超过40,var是char类型
			>::type
		> ::type
	>::type var;
	cout << "tsvar的类型为:" << typeid(decltype(var)).name() << endl;
}

在这里插入图片描述
不过这里的变量j好像只能是常量类型。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值