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

template <typename T, typename = void>
struct is_printable : std::false_type {};

template <typename T>
struct is_printable<T, std::void_t<decltype(std::cout << std::declval<T>())>> : std::true_type {};

template <typename T>
void print(const T& value) {
    if constexpr (is_printable<T>::value) {
        std::cout << "Printing: " << value << std::endl;
    } else {
        std::cout << "Cannot print this type" << std::endl;
    }
}

struct NonPrintable {};

int main() {
    print(42);
    print("Hello");
    print(NonPrintable{});

    return 0;
}
Back to template_specialization