std::conditional

定义于头文件 <type_traits>
template< bool B, class T, class F >
struct conditional;
(C++11 起)

提供成员 typedef type ,若 B 在编译时为 true 则定义为 T ,或若 Bfalse 则定义为 F

目录

成员类型

成员类型 定义
type B == true 则为 T ,若 B == false 则为 F

帮助类型

template< bool B, class T, class F >
using conditional_t = typename conditional<B,T,F>::type;
(C++14 起)

可能的实现

template<bool B, class T, class F>
struct conditional { typedef T type; };
 
template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

示例

#include <iostream>
#include <type_traits>
#include <typeinfo>
 
int main() 
{
    typedef std::conditional<true, int, double>::type Type1;
    typedef std::conditional<false, int, double>::type Type2;
    typedef std::conditional<sizeof(int) >= sizeof(double), int, double>::type Type3;
 
    std::cout << typeid(Type1).name() << '\n';
    std::cout << typeid(Type2).name() << '\n';
    std::cout << typeid(Type3).name() << '\n';
}

可能的输出:

int
double
double

参阅

(C++11)
根据编译期布尔常量隐藏一种函数重载或模板特化
(类模板)

版本历史

  • (当前 | 先前 2017年7月16日 (日) 21:47Fruderica讨论 | 贡献. . (1,525字节) (-155). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:12P12bot讨论 | 贡献 . . (1,680字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:38P12bot讨论 | 贡献 . . (1,680字节) (-94). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:11P12bot讨论 | 贡献 . . (1,774字节) (+233). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:36P12讨论 | 贡献 . . (1,541字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,541字节) (-37). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:33P12讨论 | 贡献 . . (1,578字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,578字节) (+1,578). . (Translated from the English version using Google Translate)