最終更新日時(UTC):
が更新

履歴 編集

class template
<type_traits>

std::conditional(C++11)

namespace std {
  template <bool B, class T, class F>
  struct conditional {
    using type = ;
  };

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

概要

コンパイル時条件式。

条件式がtruefalseかによって、使用する型を切り替える。

効果

conditionalは、条件式Btrueであれば型Tを、そうでなければ型Fを、メンバ型typeとして定義する。

備考

  • この機能が標準ライブラリに導入される前、Boost C++ Librariesでは、boost::mpl::if_cboost::mpl::if_という機能が使われていた。if_cが現在のconditionalであり、bool定数 (constantのc) を条件式としてとり、使用する型を分岐する。if_static const bool valueをメンバとして持つ型をパラメータとしてとる高階メタ関数であり、標準ライブラリに直接採用されてはいない
  • conditionalboost::mpl::if_cを使う以外に、テンプレートの特殊化を使用する方法もあり、conditionalboost::mpl::if_cはその手法を一般化したものである。
    template <bool>
    struct Conditional;
    
    template <>
    struct Conditional<true> {
      using type = int;
    };
    
    template <>
    struct Conditional<false> {
      using type = char;
    };
    

#include <type_traits>

static_assert(std::is_same<std::conditional<true, int, char>::type, int>::value, "select int");
static_assert(std::is_same<std::conditional<false, int, char>::type, char>::value, "select char");

int main() {}

出力

バージョン

言語

  • C++11

処理系

  • Clang: 3.0
  • GCC: 4.3.6
  • Visual C++: 2010, 2012, 2013, 2015
    • conditional_tは、2013から。

関連項目

参照