SFINAE (C++)
Substitution Failure Is Not An Error: when creating a candidate set for overload resolution, some (or all) candidates of that set may be the result of instantiated templates with (potentially deduced) template arguments substituted for the corresponding template parameters. If an error occurs during the substitution of a set of arguments for any given template, the compiler removes the potential overload from the candidate set instead of stopping with a compilation error, provided the substitution error is one the C++ standard grants such treatment. If one or more candidates remain and overload resolution succeeds, the invocation is well-formed. - An introduction
- Call a function when T has a given method (like call toString() if T has toString method)
- …
Notes on C++ SFINAE, Modern C++ and C++20 Concepts
SFINAE and enable_if are compelling features, but also it’s hard to get it right. Simple examples might work, but in real-life scenarios, you might get into all sorts of problems:
- Template errors: do you like reading template errors generated by the compiler? Especially when you use STL types?
- Readability
- Nested templates usually won’t work in enable_if statements
Here is a discussion at StackOverflow: Why should I avoid std::enable_if in function signatures
Alternatives to SFINAE
- Tag Dispatching
- Compile Time if - Since C++17
- Concepts - Since C++20
Modern C++ to the rescue
- decltype
- declval
- constexpr
- std::void_t
- detection idiom