example3_template_specialization.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
#include <iostream>
#include <type_traits>

template <typename T, typename Enable = void>
struct TypeInfo {
    static constexpr const char* name = "Unknown";
};

template <typename T>
struct TypeInfo<T, typename std::enable_if<std::is_integral<T>::value>::type> {
    static constexpr const char* name = "Integer";
};

template <typename T>
struct TypeInfo<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
    static constexpr const char* name = "Floating-point";
};

int main() {
    std::cout << "int is: " << TypeInfo<int>::name << std::endl;
    std::cout << "double is: " << TypeInfo<double>::name << std::endl;
    std::cout << "char is: " << TypeInfo<char>::name << std::endl;
    std::cout << "std::string is: " << TypeInfo<std::string>::name << std::endl;
    return 0;
}
Back to std_if_enable