skip to content

What does SFINAE mean in C++, and what happens to a function template whose signature fails substitution?

level: juniorimportance: should knowfreq 50%

answer

  1. a rule of overload resolution
  2. signature, not body
  3. bad substitution drops the candidate
  4. no candidates left, then an error

basics

~20 s

Substitution Failure Is Not An Error: if putting the template arguments into a function template's signature produces an invalid type or expression, that template is silently removed from the overload set instead of stopping the build.

solid answer

~40 s

For every function template in an overload set, the compiler deduces the template arguments and then substitutes them into the declaration: the parameter types, the return type and the template parameter list. If that substitution produces an invalid type or expression, such as `typename T::value_type` with `T = int` or `decltype(t.str())` for a type without `str()`, deduction fails for that candidate and it is simply dropped. The call still compiles if another candidate is viable; only when none is left does the compiler report `no matching function`. The rule covers the signature alone (the standard calls it the immediate context): an error inside the body of the template that wins is an ordinary hard error. `std::enable_if`, expression SFINAE with `decltype` and the `std::void_t` detection idiom are all built on this rule.

code

cpp · 28 lines
cpp
#include <iostream>
#include <sstream>
#include <string>
#include <utility>

struct Money { std::string str() const { return "12.50 EUR"; } };
struct Point { int x, y; };
std::ostream& operator<<(std::ostream& os, const Point& p) { return os << p.x << ',' << p.y; }
struct Opaque {};

// Viable only if t.str() is a valid expression.
template <class T>
auto to_string(const T& t, int) -> decltype(t.str()) { return t.str(); }

// Viable only if os << t is a valid expression.
template <class T>
auto to_string(const T& t, long) -> decltype(std::declval<std::ostream&>() << t, std::string()) {
    std::ostringstream os; os << t; return os.str();
}

// Fallback: always viable, the worst match.
template <class T>
std::string to_string(const T&, ...) { return "<opaque>"; }

int main() {
    std::cout << to_string(Money{}, 0) << ' ' << to_string(Point{1, 2}, 0) << ' '
              << to_string(Opaque{}, 0) << '\n';   // 12.50 EUR 1,2 <opaque>
}

go deeper

for a junior

Expand the acronym and say the one consequence: a template whose signature cannot be formed for these arguments drops out of overload resolution instead of failing the build.

for a middle

Walk through deduce, substitute, rank, and show one overload pair where a decltype in the return type removes a candidate; mention that the body is never consulted.

for a senior

Draw the immediate-context line precisely: helper class instantiation, deduced auto return types and noexcept specifiers produce hard errors, and you know how to restructure code so failures stay in the signature.

for a principal

Frame SFINAE as legacy machinery whose cost is unreadable diagnostics and fragile overload sets, and know when a codebase's standard level makes C++20 constraints the better tool.

## The rule in one sentence **SFINAE** stands for **Substitution Failure Is Not An Error**. It is a rule of C++ template argument deduction: when the compiler substitutes template arguments into a function template's declaration and the result would be an invalid type or expression, deduction fails for that one template and the template is quietly removed from the set of candidates. The removal itself is never reported; the call fails only if no viable candidate remains, the survivors are ambiguous, or the winner's body does not compile. ## Where substitution happens Overload resolution for a call such as `to_string(x, 0)` runs in steps: 1. Collect every function and function template named `to_string`. 2. For each template, **deduce** the template arguments from the call's arguments. 3. **Substitute** the deduced (and any explicitly given or defaulted) arguments into the declaration. 4. Rank the candidates that survived and pick the best one. The standard lists the places where substitution can fail softly. The C++26 draft calls them the *deduction substitution loci*: - the **function type** (parameter types and return type), except the `noexcept` specifier; - the `explicit` specifier; - the **template parameter declarations**, including default template arguments; - the template argument list of a **class template partial specialization**. Expressions count too, not only types: an expression inside `decltype` or `sizeof` in those places is checked, which is called **expression SFINAE** (C++11). The standard limits soft failure to the **immediate context** of those loci; anything the substitution triggers elsewhere, such as instantiating a helper class, is a real error. ## A worked example: choosing a to_string overload A pre-C++20 utility library wants `to_string` to use a `str()` member when a type has one, a stream `operator<<` when it has that, and a placeholder otherwise: ```cpp template <class T> auto to_string(const T& t, int) -> decltype(t.str()) { return t.str(); } template <class T> auto to_string(const T& t, long) -> decltype(std::declval<std::ostream&>() << t, std::string()) { /* stream it */ } template <class T> std::string to_string(const T&, ...) { return "<opaque>"; } ``` For a `Point` with only `operator<<`, substituting into the first declaration forms `t.str()`, which is invalid, so that candidate disappears; the second survives and is chosen over the ellipsis. For a type with neither, both expression-SFINAE overloads disappear and the fallback is called. The extra `int`/`long` argument breaks the tie for a type that has both: passing `0` matches `int` exactly and `long` only by conversion, so the `str()` overload is preferred. ## What SFINAE is not - **Not a general error suppressor.** An invalid expression in the **body** of the template that wins overload resolution is a hard error. - **Not triggered by a deduced `auto` return type.** `template <class T> auto f(const T& t) { return t.str(); }` has nothing invalid in its signature, so it is selected, and only then does instantiating the body fail. - **Not a library feature.** `std::enable_if` merely exploits the language rule by having no `type` member when its condition is false. - **Not a ranking tool.** SFINAE only removes candidates; the survivors are still ranked by the ordinary overload rules, which is why the example needs the `int`/`long` tie-breaker for a type that has both `str()` and `operator<<`. - **Not silent when everything fails.** If every candidate is removed, the compiler reports `no matching function for call`, and Apple clang 21 lists each candidate with the reason it was ignored. ## Common sources of substitution failure | Written in the signature | Fails when | |---|---| | `typename T::value_type` | `T` is not a class, or has no such member type | | `decltype(t.str())` | the expression `t.str()` is ill-formed for `T` | | `std::enable_if_t<Cond>` | `Cond` is `false`, so there is no `type` member | | `T*` with `T = int&` | forming a pointer to a reference is invalid | | `T[N]` with `N == 0` | arrays of size zero are invalid | ## Where it stands today SFINAE is how C++11, C++14 and C++17 code steers overload resolution by type properties. C++20 constraints (`requires`-clauses and concepts) express the same intent directly and give clearer diagnostics, but SFINAE remains everywhere in existing libraries and in interviews about pre-C++20 code, so reading it fluently is still expected.

  • Why does a deduced auto return type defeat SFINAE?
    With `auto f(const T& t) { return t.str(); }` the signature contains nothing that depends on `t.str()`, so substitution succeeds and the template can win overload resolution. The compiler must then instantiate the body to deduce the return type, and the invalid `t.str()` is a hard error there. Spell the expression in the signature, for example `-> decltype(t.str())`, to make it SFINAE-friendly.
  • Does SFINAE apply to class templates as well as function templates?
    Yes, through partial specializations. The template argument list of a partial specialization is one of the places where substitution can fail softly: if it does, that specialization simply does not match and the primary template is used. This is what the `std::void_t` detection idiom relies on. An invalid type inside a class template's member definitions, by contrast, is a hard error when that member is instantiated.

A shortlist filter: a candidate whose application form cannot even be filled in is dropped from the shortlist without cancelling the hiring round. If a hired candidate then fails at the job itself, that is a real failure, just as an error in the chosen template's body is a hard error.

  • SFINAE suppresses any compile error that occurs anywhere inside a template.
  • An invalid type in a function template's return type is always a hard error.
  • SFINAE is a feature of the std::enable_if library template, not a language rule.
  • If every candidate fails substitution, the call silently compiles to nothing.
  • The compiler checks the function body to decide whether a template is viable.