# requires expression (since C++20)

> C++ Atlas: `cppatlas.com/w/cpp/language/requires` | Source: https://en.cppreference.com/w/cpp/language/requires | Domain: Language | Standards: C++20

Yields a prvalue expression of type bool that describes the constraints.

## Executive Mental Model (Study Companion)

**Core Intuition:** Only named concepts participate in atomic constraint subsumption—writing identical raw requires expressions twice produces two distinct atoms and an ambiguous overload!

- **Standard Era:** C++17 → C++20 → C++23
- **Primary ISO Clauses:** [temp.constr], [temp.constr.order], [expr.prim.req], [temp.res]
- **CppCon Talk Angle:** Visualize overload selection as a DAG lattice: std::contiguous_iterator subsumes random_access_iterator, which subsumes bidirectional_iterator, letting std::ranges pick the fastest algorithm cleanly.
- **Common Audience Trap:** Writing requires requires(...) — the first keyword introduces a constraint clause, the second starts a boolean requires-expression.
- **Stage Takeaway:** If two constrained overloads ever tie with 'ambiguous call', check whether you wrote an ad-hoc boolean expression instead of composing named concepts.

## Memory Map Walkthrough: C++20 Concept Subsumption Lattice & Overload Resolver

C++20 concepts normalize constraints into conjunctions and disjunctions of atomic constraints. Subsumption ([temp.constr.order]) compares two constrained overloads: if constraint P logically implies constraint Q strictly because every atomic constraint in Q appears inside P from the exact same named concept definition, then P subsumes Q and wins overload resolution without ambiguity. Writing raw boolean requires clauses inline—like requires sizeof(T) > 4 && std::integral<T> vs requires std::integral<T>—works only for the shared named concept; repeating raw expressions creates separate atomic identities that never subsume each other. Meanwhile, requires-expressions check syntactic validity and return-type constraints at compile time without ever evaluating runtime operands.

### Named concepts & atomic constraint identity ([temp.constr.atomic] & [temp.constr.order])

During overload resolution, the compiler converts constrained templates into Disjunctive/Conjunctive Normal Form of atomic constraints—each tied to its exact source-code token position and parameter mapping.

If overload A writes template<class T> requires (std::integral<T> && sizeof(T) >= 4) and overload B writes template<class T> requires (std::integral<T> && sizeof(T) >= 4 && alignof(T) >= 4), the sizeof(T) >= 4 expression in A and B came from TWO separate source locations, so neither subsumes the other! Wrapping sizeof(T) >= 4 in a named concept Wide<T> shares one atomic identity.

*Subsumption works ONLY through shared named concepts:*
```cpp
template <class T>
concept SignedInt = std::integral<T> && std::is_signed_v<T>;

void dispatch(std::integral auto x); // Q: atomic(std::integral)
void dispatch(SignedInt auto x);     // P: atomic(std::integral) && atomic(is_signed)

dispatch(42); // P subsumes Q -> unambiguously calls SignedInt overload!
```

**Key takeaway:** Always factor reusable predicates into named concept declarations if you want overloads to partially order by specificity.

### The requires requires idiom decoded ([temp.constr.decl] & [expr.prim.req])

The first requires introduces a requires-clause (expecting a constant boolean expression). The second requires opens a requires-expression—an unevaluated compile-time check returning true if every nested expression compiles.

For real libraries, prefer defining a named concept above the function rather than embedding anonymous requires requires directly on every signature.

*Clean named concept vs. inline requires-requires:*
```cpp
template <class R>
concept Reservable = requires(R& r, std::size_t n) {
    r.reserve(n);       // simple requirement: must compile (not evaluated)
    { r.capacity() } -> std::convertible_to<std::size_t>; // compound requirement
};
```

**Key takeaway:** Inside a requires-expression, expressions are unevaluated operands—side effects never run, and compound requirements validate return type concepts.

## Official Specification Summary (cppreference)

Yields a prvalue expression of type `bool` that describes the constraints.

### Syntax

- `requires` `{` *requirement-seq* `}`    (1)
- `requires` `(` *parameter-list* (optional) `)` `{` *requirement-seq* `}`    (2)

- `parameter-list` - a parameter list
- `requirement-seq` - sequence of *requirements*, each requirement is one of the following:

  - simple requirement
  - type requirement
  - compound requirement
  - nested requirement

### Explanation

Requirements may refer to the template parameters that are in scope, to the parameters of *parameter-list*, and to any other declarations that are visible from the enclosing context.

The substitution of template arguments into a `requires` expression used in a declaration of a templated entity may result in the formation of invalid types or expressions in its requirements, or the violation of semantic constraints of those requirements. In such cases, the `requires` expression evaluates to `false` and does not cause the program to be ill-formed. The substitution and semantic constraint checking proceeds in lexical order and stops when a condition that determines the result of the `requires` expression is encountered. If substitution (if any) and semantic constraint checking succeed, the `requires` expression evaluates to `true`.

If a substitution failure would occur in a `requires` expression for every possible template argument, the program is ill-formed, no diagnostic required:

```cpp
template<class T>
concept C = requires
{
    new int[-(int)sizeof(T)]; // invalid for every T: ill-formed, no diagnostic required
};
```

If a `requires` expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.

### Local parameters

A `requires` expression can introduce local parameters using a parameter list. These parameters have no linkage, storage, or lifetime; they are only used as notation for the purpose of defining requirements.

The type of each parameter is determined by the same way as determining the actual type of function parameters:

```cpp
template<typename T>
concept C = requires(T p[2])
{
    (decltype(p))nullptr; // OK, p has type T*
};
```

If any of the following conditions is satisfied, the program is ill-formed:

- A local parameter has a default argument.
- The parameter list terminate with an ellipsis.

```cpp
template<typename T>
concept C1 = requires(T t = 0)  // Error: t has a default argument
{
    t;
};

template<typename T>
concept C2 = requires(T t, ...) // Error: terminates with an ellipsis
{
    t;
};
```

### Simple requirements

- *expression* `;`

- `expression` - an expression which does not start with `requires`

A simple requirement asserts that *expression* is valid. *expression* is an unevaluated operand.

```cpp
template<typename T>
concept Addable = requires (T a, T b)
{
    a + b; // "the expression “a + b” is a valid expression that will compile"
};

template<class T, class U = T>
concept Swappable = requires(T&& t, U&& u)
{
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};
```

A requirement that starts with the keyword `requires` is always interpreted as a nested requirement. Thus a simple requirement cannot start with an unparenthesized `requires` expression.

### Type requirements

- `typename` *identifier* `;`

- `identifier` - a (possibly qualified) identifier (including simple template identifier)

A type requirement asserts that the type named by *identifier* is valid: this can be used to verify that a certain named nested type exists, or that a class/alias template specialization names a type. A type requirement naming a class template specialization does not require the type to be complete.

```cpp
template<typename T>
using Ref = T&;

template<typename T>
concept C = requires
{
    typename T::inner; // required nested member name
    typename S<T>;     // required class template specialization
    typename Ref<T>;   // required alias template substitution
};

template<class T, class U>
using CommonType = std::common_type_t<T, U>;

template<class T, class U>
concept Common = requires (T&& t, U&& u)
{
    typename CommonType<T, U>; // CommonType<T, U> is valid and names a type
    { CommonType<T, U>{std::forward<T>(t)} };
    { CommonType<T, U>{std::forward<U>(u)} };
};
```

### Compound requirements

- `{` *expression* `};`    (1)
- `{` *expression* `}` `noexcept` `;`    (2)
- `{` *expression* `} ->` *type-constraint* `;`    (3)
- `{` *expression* `}` `noexcept ->` *type-constraint* `;`    (4)

- `expression` - an expression
- `type-constraint` - a constraint

A compound requirement asserts properties of *expression*. Substitution and semantic constraint checking proceeds in the following order:

1) Template arguments (if any) are substituted into *expression*.

2) If `noexcept` is present, *expression* must not be potentially throwing.

3) If *type-constraint* is present, then:

  a) Template arguments are substituted into *type-constraint*.

  b) `decltype((`*expression* `))` must satisfy the constraint imposed by *type-constraint*. Otherwise, the enclosing `requires` expression is `false`.

*expression* is an unevaluated operand.

```cpp
template<typename T>
concept C2 = requires(T x)
{
    // the expression *x must be valid
    // AND the type T::inner must be valid
    // AND the result of *x must be convertible to T::inner
    {*x} -> std::convertible_to<typename T::inner>;

    // the expression x + 1 must be valid
    // AND std::same_as<decltype((x + 1)), int> must be satisfied
    // i.e., (x + 1) must be a prvalue of type int
    {x + 1} -> std::same_as<int>;

    // the expression x * 1 must be valid
    // AND its result must be convertible to T
    {x * 1} -> std::convertible_to<T>;
};
```

### Nested requirements

- `requires` *constraint-expression* `;`

- `constraint-expression` - an expression representing constraints

A nested requirement can be used to specify additional constraints in terms of local parameters. *constraint-expression* must be satisfied by the substituted template arguments, if any. Substitution of template arguments into a nested requirement causes substitution into *constraint-expression* only to the extent needed to determine whether *constraint-expression* is satisfied.

```cpp
template<class T>
concept Semiregular = DefaultConstructible<T> &&
    CopyConstructible<T> && CopyAssignable<T> && Destructible<T> &&
requires(T a, std::size_t n)
{
    requires Same<T*, decltype(&a)>; // nested: "Same<...> evaluates to true"
    { a.~T() } noexcept; // compound: "a.~T()" is a valid expression that doesn't throw
    requires Same<T*, decltype(new T)>; // nested: "Same<...> evaluates to true"
    requires Same<T*, decltype(new T[n])>; // nested
    { delete new T }; // compound
    { delete new T[n] }; // compound
};
```

### Note

The keyword `requires` is also used to introduce `requires` clauses.

```cpp
template<typename T>
concept Addable = requires (T x) { x + x; }; // requires expression

template<typename T> requires Addable<T> // requires clause, not requires expression
T add(T a, T b) { return a + b; }

template<typename T>
    requires requires (T x) { x + x; } // ad-hoc constraint, note keyword used twice
T add(T a, T b) { return a + b; }
```

### Keywords

`requires`

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| CWG 2560 | C++20 | it was unclear whether parameter types are adjusted in `requires` expressions | also adjusted |
| CWG 2911 | C++20 | all expressions appearing within `requires` expressions were unevaluated operands | only some expressions are |

### References

- C++23 standard (ISO/IEC 14882:2024):

  - 7.5.7 Requires expressions [expr.prim.req]

- C++20 standard (ISO/IEC 14882:2020):

  - 7.5.7 Requires expressions [expr.prim.req]

### See also

- [Constraints and concepts (C++20)](https://en.cppreference.com/w/cpp/language/constraints): specifies the requirements on template arguments

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Explain why C++20 concepts are not dynamic interfaces or Rust traits, and how atomic constraint subsumption differs from boolean logic.
- Share the infamous missing-nested-requires bug where OnlyInt<double> quietly evaluates to true.
- Trace how std::ranges::advance uses iterator concept subsumption to pick O(1) pointer arithmetic over O(N) increments.

### Trap 1: [temp.constr.atomic] §13.5.1.2 (cppcon-stage)

Why does calling f(42) fail with an ambiguity error in the snippet below?

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

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

// f(42); -> Ambiguous! Why?
```

A. sizeof(T) >= 2 is not a constant expression
B. The two sizeof(T) >= 2 expressions are distinct atomic constraints, so the second overload does not subsume the first
C. std::integral<T> cannot combine with sizeof
D. Subsumption only works for class templates, not function templates

**Standard Answer (B):** The two sizeof(T) >= 2 expressions are distinct atomic constraints, so the second overload does not subsume the first

**Why:** Subsumption is syntactic/structural, NOT mathematical theorem proving. Because sizeof(T) >= 2 was written twice inline instead of factored into a single named concept, the compiler treats them as two unrelated atomic constraints.

*CppCon speaker note:* Best single-slide demonstration of what 'atomic constraint normalization' actually means in C++20.

### Trap 2: [expr.prim.req] §7.5.7 (subtle)

Inside concept HasFoo = requires(T t) { t.foo(); };, what happens if t.foo() throws or mutates global state?

A. It runs at startup during static initialization
B. Nothing—a requires-expression is an unevaluated operand evaluated purely at compile time for validity
C. Only constexpr functions are permitted inside requires
D. It compiles only if T is default-constructible

**Standard Answer (B):** Nothing—a requires-expression is an unevaluated operand evaluated purely at compile time for validity

**Why:** Operands of a requires-expression are unevaluated (just like sizeof or decltype). Function parameters like (T t) don't even require T to be constructible or movable—they are hypothetical declarations used solely for type checking.

### Trap 3: [expr.prim.req.nested] §7.5.7.4 (standard-lawyer)

Inside requires(T x) { requires std::same_as<T, int>; }, what happens if you forget the inner 'requires' keyword and write just std::same_as<T, int>;?

```cpp
template <class T>
concept OnlyInt = requires(T x) {
    std::same_as<T, int>; // Missing nested 'requires'!
};
```

A. Same meaning—the compiler checks if std::same_as<T, int> evaluates to true
B. Only checks that the expression std::same_as<T, int> is well-formed (always true for bool!), accepting double and std::string too!
C. Syntax error at compile time
D. Converts x to int

**Standard Answer (B):** Only checks that the expression std::same_as<T, int> is well-formed (always true for bool!), accepting double and std::string too!

**Why:** Without the nested 'requires', a line in a requires-expression is a simple requirement: it checks ONLY whether the expression compiles, NOT whether its boolean value is true! Since std::same_as<double, int> validly yields false (type bool), OnlyInt<double> evaluates to true!

*CppCon speaker note:* One of the deadliest C++20 concept bugs in production code—always use nested `requires` for boolean value checks.

### Trap 4: [temp.res] §13.8 (standard-lawyer)

When calling a dependent member function template on a type parameter T inside a generic function, why is `.template` needed in t.template get<0>()?

```cpp
template <class T>
auto read(T& t) {
    return t.template get<0>();
}
```

A. To tell the linker to emit weak symbols
B. So phase-1 parsing treats '<' as a template argument list instead of a less-than comparison operator
C. Only required in C++11, removed in C++20
D. To force explicit specialization

**Standard Answer (B):** So phase-1 parsing treats '<' as a template argument list instead of a less-than comparison operator

**Why:** During phase-1 template parsing, the compiler does not yet know what T is, so it assumes t.get is a non-template member and parses '<' as less-than (`(t.get < 0) > ()`). Adding `.template` disambiguates the grammar.

---
Attribution: content from https://en.cppreference.com/w/cpp/language/requires (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.