cpp / expert
Snippet
SFINAE-Based Interface Detection for Overload Resolution
Utilizes SFINAE (Substitution Failure Is Not An Error) to conditionally enable function overloads. The compiler attempts to resolve the decltype; if 'obj.to_string()' doesn't exist, the template is discarded without error, falling back to the variadic 'serialize' catch-all.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
template <typename T>auto serialize(const T& obj) -> decltype(obj.to_string(), std::string()) {return obj.to_string();}std::string serialize(...) {return "[non-serializable]";}struct Data { std::string to_string() const { return "data"; } };struct Raw { int x; };
Breakdown
1
auto serialize(const T& obj) -> decltype(obj.to_string(), std::string())
Uses trailing return type and decltype to check for the existence of the to_string() method on type T.
2
std::string serialize(...)
The C-style ellipsis provides a lower-priority overload that matches any type if the template substitution fails.