example3_conditional_compilation.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <type_traits>

// Function for integral types
template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
isEven(T value) {
    return value % 2 == 0;
}

// Function for floating-point types
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
isEven(T value) {
    return static_cast<int>(value) % 2 == 0;
}

int main() {
    std::cout << "Is 4 even? " << isEven(4) << std::endl;
    std::cout << "Is 5 even? " << isEven(5) << std::endl;
    std::cout << "Is 3.14 even? " << isEven(3.14) << std::endl;
    std::cout << "Is 4.0 even? " << isEven(4.0) << std::endl;

    // This would cause a compilation error:
    // isEven("not a number");

    return 0;
}
Back to type_traits