0Pricing
C++ Academy · Lesson

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;
}

All lessons in this course

  1. Full Specialization
  2. Partial Specialization
  3. SFINAE
  4. enable_if Patterns
← Back to C++ Academy