Calling a free function instead of a method if it doesn't exist
c++, c++11, templates
Solution
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 <class T>
auto print(S1, T const& t) -> decltype(t.write(std::cout)) {
t.write(std::cout);
}
template <class T>
auto print(S2, T const& t) -> decltype(std::cout << to_string(t)) {
std::cout << to_string(t);
}
template <class T>
void print(S3, T const& t) {
std::cout << t;
}
template <class T>
void print(T const& t) {
print(S1(), t);
}
Problem
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 { ... } }; class B { public: int val() const { ... } }; ``` suppose you need a generic free function taking a `T` returning a conventional value for whatever type NOT implementing the `val` method or calling the `val` method for ALL the types that has one: ``` template<class T> int val_of(const T& t) { return 0; } template<class T> int val_of(const T& t) { return t.val(); } ``` Consider that A and B are just samples: you don't know how many types will ever exist implementing `val`, and how many types will exist not implementing it (hence explicit specialization won't scale). Is there a simple way, based on the C++ standards, to come to a way to statically select the `val_of` version? I was thinking to a `std::conditional` or `std::enable_if`, but I didn't find a simple way to express the condition.