#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
test_01 (T i) {return bool(i%2);}

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

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

int main() {

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

    float ii = 1.1;

    std::cout << std::boolalpha;
    std::cout << test_01(i) << std::endl;
    std::cout << test_02(i) << std::endl;
    std::cout << test_03(i) << std::endl;

    // std::cout << "error: " << test_03(i) << std::endl;
    return 0;
}


备份地址: 【std::enable_if example