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

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

template<typename T>
struct has_toString<T, 
    std::void_t<decltype(std::declval<T>().toString())>> : std::true_type {};

struct WithToString {
    std::string toString() const { return "Hello"; }
};

struct WithoutToString {
    void someOtherMethod() {}
};

int main() {
    std::cout << "WithToString has toString(): " 
              << has_toString<WithToString>::value << std::endl;
    std::cout << "WithoutToString has toString(): " 
              << has_toString<WithoutToString>::value << std::endl;
    return 0;
}
Back to std_declval