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

履歴 編集

class template
<type_traits>

std::enable_if(C++11)

namespace std {
  template <bool Condition, class T = void>
  struct enable_if;

  template <bool Condition, class T = void>
  using enable_if_t = typename enable_if<Condition,T>::type; // C++14
}

概要

コンパイル時条件式が真の場合のみ有効な型。

効果

enable_ifは、Conditiontrueの場合のみ、型Tをメンバ型typeとして定義する。そうでなければenable_ifは、メンバ型typeを持たない。

enable_ifは、SFINAEと組み合わせて使用する。関数のパラメータ、戻り値型、デフォルトテンプレートパラメータ等のいずれかでenable_ifのメンバ型typeを使用することにより、テンプレートの置き換え失敗が発生し、SFINAEによってその関数がオーバーロード解決の候補から除外される。

#include <type_traits>
#include <iostream>

template <class T>
auto f(T) -> typename std::enable_if<std::is_integral<T>::value>::type
{
  std::cout << "Tは整数型" << std::endl;
}

template <class T>
auto f(T) -> typename std::enable_if<!std::is_integral<T>::value>::type
{
  std::cout << "Tは整数型以外" << std::endl;
}

int main()
{
  f(3);
  f("hello");
}

出力

Tは整数型
Tは整数型以外

バージョン

言語

  • C++11

処理系

参照