skip to content

What four kinds of requirement can a C++20 requires-expression contain, and why is `requires { sizeof(T) > 4; }` always satisfied?

level: middleimportance: should knowfreq 45%

answer

  1. simple, type, compound, nested
  2. validity is not truth
  3. decltype((E)) in compound
  4. requires inside requires

basics

~20 s

Simple (the expression compiles), type (typename X names a type), compound ({ E } with optional noexcept and -> concept) and nested (requires plus a constant that must be true). sizeof(T) > 4; is simple: it checks validity, never the value.

solid answer

~40 s

A requires-expression, `requires (params) { requirements; }`, yields `true` if every requirement holds. A **simple** requirement `a + b;` asserts only that the expression is valid. A **type** requirement `typename C::value_type;` asserts that the type exists. A **compound** requirement `{ c.size() } -> std::convertible_to<std::size_t>;` checks validity, optionally that it is not potentially-throwing with `noexcept`, and that `decltype((E))` satisfies the concept after `->`. A **nested** requirement `requires sizeof(T) > 4;` checks that a constant is `true`. So `sizeof(T) > 4;` without the leading `requires` is a simple requirement: `1 > 4` is a perfectly valid expression, so the concept accepts `std::int8_t`. Two more traps: `{ c.front() } -> std::same_as<T>` fails for `std::vector`, whose `front()` yields `const T&`; and `-> int` is ill-formed, because a type-constraint is required.

code

cpp · 26 lines
cpp
#include <concepts>
#include <cstddef>
#include <iostream>
#include <vector>

// A requires-expression with all four kinds of requirement.
template <class C>
concept SummableRange = requires(const C& c) {
    c.begin(); c.end();                                         // simple
    typename C::value_type;                                     // type
    { c.size() } -> std::convertible_to<std::size_t>;           // compound
    { *c.begin() + *c.begin() } -> std::same_as<typename C::value_type>;
    requires std::default_initializable<typename C::value_type>; // nested
};

template <SummableRange C>
typename C::value_type sum(const C& c) {
    typename C::value_type s{};
    for (const auto& x : c) s = s + x;
    return s;
}

int main() {
    std::cout << sum(std::vector<int>{1, 2, 3}) << '\n';
    static_assert(!SummableRange<std::vector<short>>);  // short + short is int
}

go deeper

for a junior

Know that a requires-expression lists operations a type must support, and that it evaluates to true or false at compile time.

for a middle

Name the four requirement kinds, write each one, and explain why a bare comparison inside the braces is only a validity check.

for a senior

Catch decltype((E)) surprises, integral promotion in same_as checks and missing nested requires in review, and choose same_as or convertible_to deliberately.

for a principal

Set the house rule for how strict public requirements are: exact types make diagnostics precise but reject reasonable callers, convertibility admits more and promises less.

## Anatomy of a requires-expression A **requires-expression** (C++20) is a `bool` prvalue that tests, at compile time, whether a list of requirements holds for some types: ```cpp requires (const C& c) { // optional parameter list: names to write expressions with /* requirements */ } ``` The parameters are never bound to real objects; like `std::declval`, they exist so that expressions can be written. Every expression in the body is an **unevaluated operand**. If substituting the template arguments into a requirement fails, the requires-expression is `false` rather than an error, which makes it the C++20 home of what detection idioms used to do. ## The four kinds | Kind | Syntax | Holds when | |---|---|---| | simple | `c.begin();` | the expression is valid | | type | `typename C::value_type;` | the named type is valid | | compound | `{ c.size() } noexcept -> std::convertible_to<std::size_t>;` | the expression is valid, not potentially-throwing if `noexcept` is written, and `decltype((E))` satisfies the type-constraint | | nested | `requires std::default_initializable<typename C::value_type>;` | the constant expression is `true` | The numeric library's summing concept uses all four: ```cpp template <class C> concept SummableRange = requires(const C& c) { c.begin(); c.end(); // simple typename C::value_type; // type { c.size() } -> std::convertible_to<std::size_t>; // compound { *c.begin() + *c.begin() } -> std::same_as<typename C::value_type>; requires std::default_initializable<typename C::value_type>; // nested }; ``` ## Trap 1: validity is not truth ```cpp template <class T> concept Wide_wrong = requires { sizeof(T) > 4; }; template <class T> concept Wide_right = requires { requires sizeof(T) > 4; }; static_assert(Wide_wrong<std::int8_t>); // passes static_assert(!Wide_right<std::int8_t>); ``` `sizeof(T) > 4;` is a simple requirement, so it asks only "does `sizeof(T) > 4` compile?". It always does. The standard adds that a requirement starting with `requires` is never a simple requirement, which is how the nested form is told apart. When the condition is a plain constant, writing it directly in the concept (`concept Wide = sizeof(T) > 4;`) is clearer still. ## Trap 2: compound requirements look at decltype((E)) The type-constraint after `->` is checked against `decltype((E))`, the expression's type **including its value category**. `std::vector<int>::front()` on a `const` vector returns `const int&`, so: - `{ c.front() } -> std::same_as<typename C::value_type>;` is **false** for `std::vector<int>`; - `{ c.front() } -> std::same_as<const typename C::value_type&>;` is true; - `{ c.front() } -> std::convertible_to<typename C::value_type>;` is usually what was meant. The part after `->` must be a **type-constraint**, a concept name with optional arguments. Writing `{ t + t } -> int;` is ill-formed; Apple clang 21 says `expected concept name with optional arguments`. ## Trap 3: the arithmetic you did not expect `SummableRange<std::vector<short>>` is false. Adding two `short` values promotes them to `int`, so `*c.begin() + *c.begin()` has type `int`, not `short`, and the `std::same_as` check fails. A requirement written with `std::same_as` documents the exact type an algorithm relies on; if any type that converts back is acceptable, `std::convertible_to` is the honest constraint. ## requires requires A requires-expression can be used directly in a requires-clause: ```cpp template <class T> requires requires (T a) { a.normalize(); } void tidy(T& value); ``` - The first `requires` starts the **clause**, the second starts the **expression**. - It is legal, but an ad-hoc expression has no name for diagnostics or reuse, and two overloads written this way never order by subsumption. - Prefer naming the requirement as a concept once it is used in more than one place. ## Requires-expressions outside a requires-clause Because a requires-expression is just a `bool` constant, it can appear anywhere a constant is allowed inside a template, for example to branch: ```cpp template <class C> void grow(C& c) { if constexpr (requires { c.reserve(10); }) c.reserve(10); } ``` `grow(text)` reserves for a `std::string`, and `grow(n)` with an `int` simply skips the call. Two limits apply: 1. The soft "false instead of an error" behaviour needs a **dependent** expression. Outside any template, `static_assert(!requires { n.reserve(1); });` with an `int n` is a hard error; Apple clang 21 reports `member reference base type 'int' is not a structure or union`. 2. If a requirement could never be satisfied for any template argument, the program is ill-formed, no diagnostic required, so a probe must be one that some type can pass.

  • What does noexcept add to a compound requirement?
    Writing `{ a.swap(b) } noexcept;` additionally requires that the expression is not potentially-throwing, as the `noexcept` operator would judge it. A type whose `swap` is not declared `noexcept` then fails the requirement even though the call compiles, which lets an algorithm demand a non-throwing operation in its constraints.
  • When would you write a type requirement rather than a compound one?
    Use `typename C::value_type;` when the algorithm needs a nested type or alias template specialization to exist and nothing about expressions. A type requirement is also how you check that a template-id such as `typename Traits<T>::type` can be formed. Compound requirements are for expressions whose result type or exception behaviour matters.

  • A simple requirement like sizeof(T) > 4; checks that the condition is true.
  • A compound requirement checks the declared return type with references removed.
  • { E } -> int; requires the expression to be convertible to int.
  • requires requires is a typo for a single requires.
  • The expressions in a requires-expression run at program start-up.

Assumes C++20 or later: requires-expressions and their four requirement kinds are C++20 features.