Suppose you have a family of type-unrelated classes implementing a common concept by means of a given method returning a value:
class A { public: int val() const
Just a somewhat longer comment... Your question has been answered. But I recently had a similar problem. Say you want to write a method to print strings to cout: Use member function write(std::cout), if not available use free function to_string(), if not available fallback to operator<<. You can use expression SFINAE as in the answer and a little class hierarchy to disambiguate the overloads:
struct S3 {};
struct S2 : S3 {};
struct S1 : S2 {};
template
auto print(S1, T const& t) -> decltype(t.write(std::cout)) {
t.write(std::cout);
}
template
auto print(S2, T const& t) -> decltype(std::cout << to_string(t)) {
std::cout << to_string(t);
}
template
void print(S3, T const& t) {
std::cout << t;
}
template
void print(T const& t) {
print(S1(), t);
}