目录
1. 说明
定义:
template< bool B, class T, class F >
struct conditional;
标准库模板conditional 是两个备选方案之间的编译时选择器,提供了成员的typedef 类型。如果其第一个参数B求值为真,则结果(以成员type表示)为第二个参数T;否则,结果为第三个参数F。如果程序在 conditional 中加入了特化,则行为未定义。
成员:
type | T if B == true, F if B == false |
帮助类型:
template< bool B, class T, class F > | (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