Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 171 ยท Templates and Generic Programming

SFINAE and Overload Resolution

Learn how C++ picks between overloads and templates, what substitution failure is not an error means, and how enable_if, void_t, decltype and priority tags select code at compile time.

When you call print(x) and several functions are named print, the compiler has to pick one. That process is overload resolution, and it has precise rules. When some of the candidates are templates, a second process runs first: the compiler tries to substitute your argument types into each template, and templates whose signatures become invalid are quietly dropped. This rule is called SFINAE, "substitution failure is not an error", and for decades it was the main tool for making a function template appear only for the right types.

This lesson explains both steps in detail. You will learn how the compiler ranks conversions, why a template can beat a non-template, how std::enable_if, std::void_t, decltype and priority tags use SFINAE, and where concepts and if constexpr replace all of it in modern code. Even if you write only modern C++, you will meet SFINAE in existing libraries and in error messages, so it is worth understanding. It builds on Function Overloading, Function Templates and Type Traits and Metaprogramming.

How the compiler chooses a function

For a call such as f(arg), the compiler works in stages:

flowchart TD
    A["Find all functions and templates<br/>named f (name lookup)"] --> B["For each template:<br/>deduce arguments, substitute them"]
    B -->|"substitution fails"| X["Template is removed<br/>(SFINAE, no error)"]
    B -->|"substitution works"| C["Viable candidates"]
    A --> C
    C --> D["Keep functions whose parameters<br/>accept the arguments"]
    D --> E["Rank the argument conversions"]
    E --> F{"One candidate is better<br/>for every argument?"}
    F -->|"yes"| G["Call it"]
    F -->|"tie"| H["Prefer non-template,<br/>then more specialized template"]
    F -->|"no clear winner"| I["Error: ambiguous call"]
    H --> G

The stages of a function call. SFINAE happens at the substitution step; ranking comes afterward.

Remember the order: SFINAE decides which functions are candidates, ranking decides which candidate wins. A deleted function still takes part in ranking, and if it wins, the call fails to compile.

Ranking conversions

For each argument, the compiler asks how much conversion is needed to reach the parameter type. The sequences are ranked from best to worst:

  1. Exact match: same type, or only trivial changes such as array-to-pointer, adding const to a pointee, or binding a reference.
  2. Promotion: char, short or bool to int; float to double.
  3. Conversion: any other standard conversion, such as int to double, double to int, or int* to bool.
  4. User-defined conversion: through a converting constructor or conversion operator.
  5. Ellipsis: matching ... in a C-style variadic function.

A candidate is better if no argument is worse and at least one is better. If two candidates tie on every argument, then a non-template function beats a template, and a more specialized template beats a more general one. If still tied, the call is ambiguous and you get an error.

The next example makes the surprising rule visible: a template with an exact match beats a non-template that needs a promotion or a conversion.

C++ Which overload wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

f('a') surprises many people: they expect f(int) because "a character is an int". But a promotion is worse than an exact match, and the template can match char exactly. The lesson here is to be careful when you mix generic templates with ordinary overloads: the template can swallow calls you meant for the specific function. Constraining the template, which is what the rest of this lesson is about, is the fix.

What SFINAE means

During template argument deduction, the compiler replaces template parameters with the deduced types in the function's signature: the return type, the parameter types, and default template arguments. If that replacement yields an invalid type or expression, such as int::value_type or T* where T is a reference, the compiler does not report an error. It simply discards that template for this call. Only if no candidate remains do you see "no matching function".

C++
template <typename T>
typename T::value_type first(const T& container) {   // return type needs T::value_type
    return *container.begin();
}

int first(const int (&array)[3]) { return array[0]; }

// first(std::vector<int>{1, 2, 3})  -> template works
// first(arr)                        -> template fails to substitute (int[3] has no value_type), array overload is used

The key limit: only failures in the immediate context (the signature) count. An error inside the function body, or inside the instantiation of another template, is a hard error and aborts compilation. This is why C++ error messages for templates are so long: the compiler got past the signature and failed deep inside.

std::enable_if: switching templates on and off

std::enable_if_t<Condition, Type> is Type when the condition is true and an invalid expression when it is false. Put it in the signature, and the template exists only when the condition holds. There are three common places for it. The version in a defaulted non-type template parameter is the most robust, and the one to remember:

C++ enable_if selects overloads by type category

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Why does form 1 avoid the trap in form 3? The two templates in form 1 have different types for their third template parameter after substitution (enable_if_t<A, int> versus enable_if_t<B, int> are different dependent types), so they are different templates. In form 3, only a default argument differs, and default arguments are not part of a template's identity.

Notice describe(true): bool is an integral type, so it takes the integer branch and prints 1. SFINAE is exact about categories, not about intent.

Detecting expressions: void_t and decltype

enable_if tests a trait that already exists. To ask "does x.size() compile?" you test the expression itself. Two tools do it:

  • Trailing return type with decltype: auto f(const C& c) -> decltype(c.size()) is only valid if c.size() is.
  • std::void_t: an alias that maps any valid list of types to void. Put an expression inside it in a partial specialization, and the specialization is chosen exactly when the expression is valid. This is called the detection idiom.
C++ Detecting member functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In has_size<int[3]> the expression std::declval<const int(&)[3]>().size() is invalid, so the specialization is discarded and the primary template (false_type) is used. std::declval appears again here: it lets you write an expression on a type without constructing one (Type Traits explains it).

Choosing among several: priority tags

Sometimes several overloads are all valid and you want a preference order, for example "use to_string if possible, else construct a string, else give up". Overload ranking gives you the mechanism: add an extra parameter of a type from an inheritance chain. The overload whose tag is the most derived wins, because converting to a base class is a worse conversion.

C++ Priority tags for a fallback chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

For stringify(Opaque{}) the first two templates fail substitution (no std::to_string(Opaque), no std::string(Opaque)), so only rank<0> remains. For 42, all of rank<2> applies; rank<1> does not (an int cannot construct a string), and rank<2> is the closest tag match anyway. This pattern also shows why SFINAE ties into overloading: ordinary overload ranking, not special compiler magic, picks the winner.

The modern replacements

Most of this machinery exists because C++ had no direct way to say "this template requires that". Two features now do it better.

if constexpr (C++17) chooses between code paths inside one function. The discarded branch is not instantiated, so it can use operations the type does not have:

C++
template <typename T>
std::string describe(const T& value) {
    if constexpr (std::is_integral_v<T>) {
        return "integer " + std::to_string(value);
    } else if constexpr (std::is_floating_point_v<T>) {
        return "floating-point " + std::to_string(value);
    } else {
        return "something else";
    }
}

Concepts and requires (C++20) constrain the template itself, with readable names, readable error messages, and automatic ranking by "more constrained wins":

C++
template <std::integral T>
std::string describe(T value) { return "integer " + std::to_string(value); }

template <std::floating_point T>
std::string describe(T value) { return "floating-point " + std::to_string(value); }

template <typename C>
    requires requires(const C& c) { c.size(); }
auto length(const C& c) { return c.size(); }

Use concepts in new code whenever your compiler supports C++20 (Concepts), if constexpr for branching inside one function, and SFINAE only when you must support pre-C++20 compilers or are reading code that does.

Common mistakes

  • Errors in the body are not SFINAE. template<class T> auto f(T t) { return t.missing(); } has a deduced return type, so the body is needed to find the signature, and a failure there is a hard error. Use a trailing decltype if you want the failure to be soft.
  • Forgetting that ranking can still pick a bad template. An unconstrained template <typename T> void f(T) outcompetes non-template overloads that need a promotion (see the first example). Constrain it.
  • Two templates with the same signature. The typename = enable_if_t<...> form from the example makes two templates that differ only in default arguments, which is a redeclaration error.
  • Ambiguity. If two constrained templates are both viable and neither is more specialized, the compiler reports an ambiguous call. Make the conditions mutually exclusive, or use concepts that subsume each other.
  • Making the condition depend on non-deduced context. The condition must involve the template parameters; otherwise the compiler evaluates it immediately (a hard error, not a soft one).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given void f(int) and template <typename T> void f(T), which is called by f('a')?

    Passing char to int needs a promotion, while the template matches char exactly. Exact match is ranked higher, so the template wins.
  2. 2. What does SFINAE do when substituting deduced types into a template's signature gives an invalid type?

    Substitution failure in the immediate context is not an error. The template just stops being a candidate; an error appears only if no candidate is left.
  3. 3. Which is a soft (SFINAE-friendly) failure?

    The signature is the immediate context, so an invalid decltype there removes the overload. Errors in the body happen after overload selection and are hard errors.
  4. 4. Why do two templates that differ only by "typename = std::enable_if_t<...>" defaults fail to compile?

    Their template parameter lists are identical apart from defaults. Use a defaulted non-type parameter (enable_if_t<cond, int> = 0) so the declarations differ.
  5. 5. In the priority-tag pattern, why does an overload taking rank<2> win over one taking rank<1> when both are viable?

    The argument rank<2>{} matches rank<2> exactly. Matching rank<1> needs a derived-to-base conversion, which ranks lower, so rank<2> is the better candidate.

Summary

  • Overload resolution first builds the candidate set (templates that fail substitution are dropped by SFINAE), then ranks conversions: exact, promotion, conversion, user-defined, ellipsis.
  • Ties are broken in favor of non-templates, then more specialized templates; no clear winner means an ambiguous-call error.
  • An unconstrained template can beat a non-template that needs a promotion, such as f('a') choosing template f(T) over f(int).
  • Only invalid types or expressions in a template's signature are soft failures; errors in the body are hard errors.
  • std::enable_if_t<cond, int> = 0 as a template parameter, trailing decltype, and std::void_t detection let you enable overloads only for suitable types; priority tags express a preference order.
  • Prefer concepts (C++20) and if constexpr (C++17) in new code; they say the same thing with clearer code and errors.

Next: The Standard Template Library, where containers, iterators and algorithms come together.