# SFINAE and Concepts

> Trace how substitution failures prune candidates silently during C++17 template deduction, and how C++20 concepts replace enable_if with named atomic constraints and subsumption.

- **Source:** C++ Atlas (https://cppatlas.com/topics/sfinae-and-concepts)
- **Track:** Templates
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [temp.deduct] (https://eel.is/c++draft/temp.deduct), [temp.constr.decl] (https://eel.is/c++draft/temp.constr.decl), [temp.constr.atomic] (https://eel.is/c++draft/temp.constr.atomic), [temp.constr.order] (https://eel.is/c++draft/temp.constr.order), [expr.prim.req] (https://eel.is/c++draft/expr.prim.req), [over.match.viable] (https://eel.is/c++draft/over.match.viable), [meta.trans.other] (https://eel.is/c++draft/meta.trans.other)
- **cppreference links:** [SFINAE](https://en.cppreference.com/w/cpp/language/sfinae), [Constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints), [requires expression](https://en.cppreference.com/w/cpp/language/requires), [std::enable_if](https://en.cppreference.com/w/cpp/types/enable_if), [std::void_t](https://en.cppreference.com/w/cpp/types/void_t), [Concepts library](https://en.cppreference.com/w/cpp/concepts), [Overload resolution](https://en.cppreference.com/w/cpp/language/overload_resolution)
- **Prerequisites:** overload-resolution, type-deduction-auto-decltype

Overload resolution across function templates requires a way to tell the compiler which type combinations a template actually supports. Before C++20, authors relied on **SFINAE** ("Substitution Failure Is Not An Error") to sabotage template signatures intentionally when types did not fit; C++20 replaced those tricks with **concepts**, turning constraints into first-class compile-time predicates with formal partial ordering.

## SFINAE and the immediate context boundary

When overload resolution tests a function template candidate, it substitutes deduced or explicit template arguments into the template's **immediate context**—its template parameter list, function parameter types, return type, `explicit(expr)`, and `noexcept(expr)` (`[temp.deduct]`). If substituting `T = int` makes the signature invalid (such as forming `int::iterator` or dividing by zero in a constant expression inside the signature), the compiler does **not** emit a compile error. Instead, it drops that candidate silently from the viable overload set.

Crucially, SFINAE stops at the immediate context boundary. Any error triggered while instantiating a helper **class template body** or the function's own body is a **hard error**, even if that instantiation began during signature substitution. For example, checking `typename Wrapper<T>::type` only invokes SFINAE if `Wrapper<T>` fails directly on `::type` lookup; if instantiating `Wrapper<T>` itself fails inside its member declarations, compilation aborts immediately.

## Pre-C++20 idioms: enable_if, void_t, and expression SFINAE

Three pre-C++20 idioms operationalized SFINAE across libraries:

- **`std::enable_if_t<Cond, T>`:** Defined only when `Cond` is `true` (`[meta.trans.other]`). When `Cond` is `false`, referencing `enable_if<false>::type` fails substitution cleanly.
- **`std::void_t<Args...>`:** Maps any pack of valid types to `void`, powering trait detection via partial class template specialization.
- **Expression SFINAE and `if constexpr`:** Placing `decltype(expr, void())` in a trailing return type tests valid expressions without calling them, while C++17 `if constexpr` discards untaken branches inside a single function body.

```cpp
#include <type_traits>
#include <utility>
#include <vector>

template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
int classify(T) { return 1; }

template <class T, std::enable_if_t<!std::is_integral_v<T>, int> = 0>
int classify(T) { return 2; }

template <class, class = void>
struct has_size : std::false_type {};

template <class T>
struct has_size<T, std::void_t<decltype(std::declval<const T&>().size())>>
    : std::true_type {};

static_assert(has_size<std::vector<int>>::value);
static_assert(!has_size<int>::value);
```

> **Pitfall.** Never write `template <class T, class = std::enable_if_t<Cond>> void f(T);` to distinguish two overloads. Default template arguments are **not** part of a function template's signature, so two overloads differing only in their default `enable_if_t` type redeclare the exact same function template and fail to compile. Use a non-type template parameter (`std::enable_if_t<Cond, int> = 0`) or constrain the return type instead.

## C++20 constraints, concepts, and requires-expressions

C++20 concepts move constraining predicates into explicit boolean compile-time clauses checked **before** overload conversion ranking (`[over.match.viable]`), producing readable diagnostics and eliminating manual mutual-exclusion flags (`!CondA && CondB`).

A template accepts constraints in four equivalent syntactic positions: constrained template-head parameters (`template <std::integral T>`), a `requires`-clause after the template parameter list, a trailing `requires`-clause after the function declarator (essential for constraining non-template member functions of class templates without turning them into templates), or abbreviated function templates (`void f(std::integral auto x)`).

A `requires`-expression (`[expr.prim.req]`) lets a concept or `requires`-clause test compile-time syntax directly using four kinds of requirements:

| Requirement kind | Syntax example | What it verifies |
| --- | --- | --- |
| Simple requirement | `a + b;` | Expression is well-formed (unevaluated) |
| Type requirement | `typename T::value_type;` | Nested type or specialization exists |
| Compound requirement | `{ c.size() } noexcept -> std::convertible_to<std::size_t>;` | Expression compiles, optional `noexcept`, return satisfies concept |
| Nested requirement | `requires !std::is_pointer_v<T>;` | Constant boolean expression evaluates to `true` |

```cpp
#include <concepts>
#include <cstddef>
#include <type_traits>

template <class C>
concept SizedContainer = requires(const C& c) {
    typename C::value_type;
    c.begin();
    { c.size() } noexcept -> std::convertible_to<std::size_t>;
    requires !std::is_pointer_v<C>;
};
```

Writing `requires requires(T x) { ... }` directly on a function combines two separate grammar tokens: the first `requires` starts a `requires`-clause (expecting a boolean constant expression), while the second starts a `requires`-expression that evaluates to `bool`. Factor reusable predicates into named `concept` declarations instead of scattering anonymous `requires requires` clauses across signatures.

> **Pitfall.** Inside a `requires`-expression, omitting the nested `requires` keyword turns a boolean trait check into a simple requirement! Writing `std::same_as<T, int>;` without a leading `requires` only tests whether the expression `std::same_as<T, int>` compiles—and since it validly produces a `bool` (even `false`), the requirement passes for `double` too.

## Constraint normalization and subsumption

SFINAE cannot rank overlapping conditions—if two overloads both accept `int`, overload resolution fails with ambiguity unless you explicitly negate one condition inside the other. Concepts solve that via **subsumption** (`[temp.constr.order]`): if two constrained candidates match equally well on parameter conversions, the **more constrained** candidate wins automatically.

> **Mental model.** Subsumption does not inspect runtime semantics or algebra; it treats named concepts as reusable building blocks. Candidate `P` subsumes candidate `Q` only when every atomic constraint in `Q` appears inside `P` from the exact same named concept declaration.

During comparison, the compiler normalizes each candidate's constraint expression into conjunctions (`&&`) and disjunctions (`||`) of **atomic constraints** (`[temp.constr.atomic]`). An atomic constraint is identified by both its source-code expression location and its template parameter mapping—meaning two inline `sizeof(T) >= 4` expressions in separate `requires` clauses create two distinct atomic constraints that **never** subsume one another!

```cpp
#include <concepts>
#include <type_traits>

template <class T>
concept Integral = std::integral<T>;

template <class T>
concept SignedIntegral = Integral<T> && std::is_signed_v<T>;

constexpr int pick(Integral auto) { return 1; }
constexpr int pick(SignedIntegral auto) { return 2; } // subsumes Integral!

static_assert(pick(42u) == 1);
static_assert(pick(42) == 2);
```

> **Standardese.** Under `[temp.constr.atomic]`, only concept-ids expand recursively during constraint normalization; constant expressions involving type traits like `std::is_signed_v<T> && std::is_integral_v<T>` are opaque single atoms unless composed from named `concept` declarations.

Because `SignedIntegral<T>` expands directly to the shared named concept `Integral<T>` conjoined with `std::is_signed_v<T>`, `pick(SignedIntegral auto)` strictly subsumes `pick(Integral auto)` and resolves `pick(42)` without ambiguity. Note also that since C++23 (`P2593R1`), `static_assert(false)` inside an uninstantiated `if constexpr` branch or template body is valid until instantiated, complementing concepts for clean compile-time error messages.

## What to remember

- SFINAE applies only within the immediate context of template substitution; errors inside instantiated class or function bodies remain hard errors.
- Avoid `class = std::enable_if_t<...>` as a default template argument for overloading—it creates duplicate signatures; use non-type template parameters or constraints instead.
- Inside a `requires`-expression, expressions are unevaluated; always prefix boolean predicate assertions with nested `requires` so you check truth value, not mere syntactic validity.
- Factor shared predicates into named `concept` definitions—subsumption matches normalized atomic constraints by declaration identity, not boolean equivalence.
- Constraint satisfaction filters candidates before conversion ranking, and a more constrained candidate beats a less constrained one cleanly without ambiguity.

## Concept Map Outline

- **SFINAE & Concepts:** Compile-time template constraints evolved from silent SFINAE substitution failures to ordered C++20 concept lattices.
  - **SFINAE Rules:** Invalid type or expression formation in a signature drops a candidate without failing the build.
    - **Immediate Context:** Template parameters, function parameters, return types, and explicit/noexcept clauses participate in SFINAE.
    - **Hard Instantiation Errors:** Failures inside instantiated helper class bodies or function bodies halt compilation immediately.
    - **Expression SFINAE:** Trailing decltype expressions verify member calls or operators without evaluating operands.
  - **Pre-C++20 Idioms:** Library patterns built explicit opt-in and trait detection on top of SFINAE.
    - **std::enable_if:** Produces a nested type only when a compile-time boolean condition evaluates to true.
    - **Default Arg Signature Trap:** Overloads differing only by a default template type argument collide as identical redeclarations.
    - **std::void_t Detection:** Maps valid type expressions to void to select specialized type traits cleanly.
    - **if constexpr Branches:** Discards untaken compile-time branches inside a single template body since C++17.
  - **C++20 Syntax:** Constraints evaluate before overload conversion sequences and yield clear diagnostics.
    - **Named Concepts:** Reusable compile-time boolean predicates that serve as shared atoms for subsumption.
    - **Requires-Clauses:** Attach compile-time boolean constraints on template heads or trailing member signatures.
    - **Abbreviated Auto:** Constrained auto parameters synthesize constrained function templates concisely.
    - **Requires-Expressions:** Evaluate syntactic validity of expressions and types at compile time, returning a bool.
  - **Requirement Kinds:** Inside a requires-expression, four distinct clauses check syntax, types, returns, and values.
    - **Simple & Type:** Verify that expressions compile and nested or specialized types exist without evaluating operands.
    - **Compound Return Check:** Enforce expression validity, optional noexcept guarantee, and return type concept satisfaction.
    - **Nested Requires Trap:** Omitting nested requires checks only whether a boolean trait expression compiles, not whether it is true.
  - **Subsumption Ordering:** Overlapping constrained templates resolve ambiguity through normalized atomic constraint inclusion.
    - **Atomic Constraints:** Constraints normalize down to source-located predicates paired with their template parameter mapping.
    - **DNF and CNF Normalization:** The compiler expands named concepts into conjunctions and disjunctions before comparing candidates.
    - **More Constrained Wins:** A candidate whose normalized constraints include all of another's wins overload resolution cleanly.

## Standardese Quiz Questions

### Question 1 [warmup] ([temp.deduct], [meta.trans.other])

During overload resolution, what happens when `std::enable_if_t<false, int>` is formed in a function template's return type?

A. Compilation halts immediately with an error inside namespace std
B. Substitution fails in the immediate context and that candidate is silently removed from the overload set
C. The return type defaults to void and the template remains viable
D. std::enable_if_t throws std::bad_typeid at runtime

**Answer (B):** Substitution fails in the immediate context and that candidate is silently removed from the overload set

**Why:** Under [temp.deduct], when `Cond` is false, `std::enable_if<false, int>` has no member `type`. Because this failure occurs in the immediate context of the function template's return type, SFINAE removes the candidate silently.

### Question 2 [warmup] ([dcl.fct], [temp.constr.decl])

How do `template <class T> void f(T x) requires std::integral<T>;` and `void f(std::integral auto x);` compare in C++20?

A. Both declare function templates constrained by std::integral on the deduced parameter type
B. Only the abbreviated form works with concepts; trailing requires only checks runtime values
C. Abbreviated auto allows virtual member functions whereas trailing requires forbids them
D. Abbreviated auto performs type erasure like std::any instead of template instantiation

**Answer (A):** Both declare function templates constrained by std::integral on the deduced parameter type

**Why:** Under [dcl.fct] and [temp.constr.decl], an abbreviated function template using a type-constraint before `auto` introduces an invented constrained template type parameter with the same constraint semantics.

### Question 3 [tricky] ([temp.over.link], [temp.param])

Why does defining these two overloads with default template type arguments fail to compile?

```cpp
template <class T, class = std::enable_if_t<std::is_integral_v<T>>>
void log(T v) {}

template <class T, class = std::enable_if_t<!std::is_integral_v<T>>>
void log(T v) {}
```

A. std::enable_if_t cannot be placed inside a template parameter list
B. Both conditions evaluate to true when T is int
C. Default template arguments are not part of a function template's signature, so the second declaration redefines the first
D. is_integral_v requires C++20 concepts to negate

**Answer (C):** Default template arguments are not part of a function template's signature, so the second declaration redefines the first

**Why:** Two function templates with identical parameter lists and template parameter kinds have the exact same signature regardless of default template arguments ([temp.over.link]). The second `log` illegally redefines the first template with a different default argument.

### Question 4 [tricky] ([expr.prim.req.simple], [expr.prim.req.nested])

What does `AlwaysTrue<double>` evaluate to in the concept definition below?

```cpp
template <class T>
concept AlwaysTrue = requires {
    std::same_as<T, int>;
};
```

A. false, because double is not the same type as int
B. Ill-formed: concepts cannot appear inside a requires-expression
C. false, because std::same_as evaluates at runtime
D. true, because without a nested `requires`, the line only checks whether the expression `std::same_as<double, int>` compiles

**Answer (D):** true, because without a nested `requires`, the line only checks whether the expression `std::same_as<double, int>` compiles

**Why:** Inside a requires-expression, `std::same_as<T, int>;` without a leading `requires` is a simple requirement ([expr.prim.req.simple]). Since `std::same_as<double, int>` is a valid bool expression yielding `false`, the simple requirement succeeds and `AlwaysTrue<double>` is `true`!

### Question 5 [standardese] ([temp.constr.atomic], [temp.constr.order])

Why is calling `pick(42)` ambiguous between these two constrained overloads?

```cpp
template <class T> requires (sizeof(T) >= 2)
void pick(T) {}

template <class T> requires (sizeof(T) >= 2 && std::integral<T>)
void pick(T) {}
```

A. sizeof(T) >= 2 is not a constant expression when T is deduced
B. The two inline `sizeof(T) >= 2` expressions are separate atomic constraints with distinct source identities, so neither subsumes the other
C. Subsumption only applies to class templates, never function templates
D. std::integral<T> cannot be combined with && inside a requires clause

**Answer (B):** The two inline `sizeof(T) >= 2` expressions are separate atomic constraints with distinct source identities, so neither subsumes the other

**Why:** Under [temp.constr.atomic] and [temp.constr.order], subsumption compares normalized atomic constraints by declaration identity and parameter mapping—not mathematical equivalence. Only factoring `sizeof(T) >= 2` into a shared named concept enables subsumption.

### Question 6 [standardese] ([temp.deduct])

Which failure triggers a hard compilation error rather than being silently discarded by SFINAE when instantiating for `T = int`?

A. Forming `typename T::value_type` directly in a function template's return type
B. Forming an invalid call `decltype(std::declval<T&>().push_back(0))` in a trailing return type
C. A static_assert or invalid typedef triggered inside a helper struct's class definition instantiated during substitution
D. Failing a concept check in a function template's trailing requires-clause

**Answer (C):** A static_assert or invalid typedef triggered inside a helper struct's class definition instantiated during substitution

**Why:** Under [temp.deduct], SFINAE covers only errors in the immediate context of the function type and template parameter expressions. Instantiating a separate class template body to inspect its members leaves the immediate context and causes a hard error.
