<type_traits>

类模板
<type_traits>

std::enable_if

template <bool Cond, class T = void> struct enable_if;
Enable type if condition is met
The typeTis enabled as member typeenable_if::typeifCondis true.

否则,enable_if::typeis not defined.

This is useful to hide signatures on compile time when a particular condition is not met, since in this case, the memberenable_if::typewill not be defined and attempting to compile using it should fail.

It is defined with a behavior equivalent to
1
2
template<bool Cond, class T = void> struct enable_if {};
template<class T> struct enable_if<true, T> { typedef T type; };

模板参数

Cond
A compile-time constant of typebool.
T
一个类型。

成员类型

成员类型定义
类型T
(defined only ifCondis true)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// enable_if example: two ways of using enable_if
#include <iostream>
#include <type_traits>

// 1. the return type (bool) is only valid if T is an integral type:
template <class T>
typename std::enable_if<std::is_integral<T>::value,bool>::type
  is_odd (T i) {return bool(i%2);}

// 2. the second template argument is only valid if T is an integral type:
template < class T,
           class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even (T i) {return !bool(i%2);}

int main() {

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

  std::cout << std::boolalpha;
  std::cout << "i is odd: " << is_odd(i) << std::endl;
  std::cout << "i is even: " << is_even(i) << std::endl;

  return 0;
}

输出
i is odd: true
i is even: false


另见