理解C++标准库模板:conditional

目录

1.  说明

2.  示例


1.  说明

定义:

template< bool B, class T, class F >

struct conditional;

标准库模板conditional 是两个备选方案之间的编译时选择器,提供了成员的typedef 类型。如果其第一个参数B求值为真,则结果(以成员type表示)为第二个参数T;否则,结果为第三个参数F如果程序在 conditional 中加入了特化,则行为未定义。

成员:

type

T if == trueF if == false

帮助类型:

template< bool B, class T, class F >
using conditional_t = typename conditional<B,T,F>::type;

(since C++14)

可能的定义:

//默认true

template <bool _Test, class _Ty1, class _Ty2>

struct conditional { // Choose _Ty1 if _Test is true, and _Ty2 otherwise

    using type = _Ty1;

};

//特化false

template <class _Ty1, class _Ty2>

struct conditional<false, _Ty1, _Ty2> {

    using type = _Ty2;

};

2.  示例

例1 :

// conditional example

#include <iostream>

#include <type_traits>

int main() {

  short int i = 1;    // code does not compile if type of i is not integral

  typedef std::conditional<true,int,float>::type A;                      // int

  typedef std::conditional<false,int,float>::type B;                     // float

  typedef std::conditional<std::is_integral<A>::value,long,int>::type C; // long

  typedef std::conditional<std::is_integral<B>::value,long,int>::type D; // int

  std::cout << std::boolalpha;

  std::cout << "typedefs of int:" << std::endl;

  std::cout << "A: " << std::is_same<int,A>::value << std::endl;

  std::cout << "B: " << std::is_same<int,B>::value << std::endl;

  std::cout << "C: " << std::is_same<int,C>::value << std::endl;

  std::cout << "D: " << std::is_same<int,D>::value << std::endl;

  return 0;

}

输出:

typedefs of int:

A: true

B: false

C: false

D: true

例2 :

#include <iostream>

#include <type_traits>

#include <typeinfo>

 int main()

{

    using Type1 = std::conditional<true, int, double>::type;

    using Type2 = std::conditional<false, int, double>::type;

    using Type3 = std::conditional<sizeof(int) >= sizeof(double), int, double>::type;

    std::cout << typeid(Type1).name() << '\n';

    std::cout << typeid(Type2).name() << '\n';

    std::cout << typeid(Type3).name() << '\n';

}

可能输出:

int

double

double

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值