SFINAE
Enable functions conditionally.
What Does SFINAE Mean?
SFINAE stands for "Substitution Failure Is Not An Error". When the compiler substitutes template arguments and the result is ill-formed, that candidate is simply removed rather than causing a hard error.
- It enables conditional overloads.
- It is the basis of compile-time selection.
#include <iostream>
#include <type_traits>
template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
isOdd(T n) { return n % 2 != 0; }
int main() {
std::cout << std::boolalpha << isOdd(3) << '\n';
return 0;
}Substitution Failure in Action
If substituting a type makes a function's signature invalid, the compiler quietly skips it and keeps looking at other candidates.
#include <iostream>
template <typename T>
auto sizeOfValue(T t) -> decltype(t.size()) { return t.size(); }
int main() {
std::string s = "hello";
std::cout << sizeOfValue(s) << '\n';
return 0;
}