# Concepts library (since C++20)

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

The concepts library provides definitions of fundamental library concepts that can be used to perform compile-time validation of template arguments and perform function dispatch based on properties of types.

## 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)

The concepts library provides definitions of fundamental library concepts that can be used to perform compile-time validation of template arguments and perform function dispatch based on properties of types. These concepts provide a foundation for equational reasoning in programs.

Most concepts in the standard library impose both syntactic and semantic requirements. It is said that a standard concept is *satisfied* if its syntactic requirements are met, and is *modeled* if it is satisfied and its semantic requirements (if any) are also met.

In general, only the syntactic requirements can be checked by the compiler. If the validity or meaning of a program depends whether a sequence of template arguments models a concept, and the concept is satisfied but not modeled, or if a semantic requirement is not met at the point of use, the program is ill-formed, no diagnostic required.

### Equality preservation

An expression is *equality-preserving* if it results in equal outputs given equal inputs, where

- the inputs consist of its operands (not neccessarily making the expression semantically valid), and
- the outputs consist of its result and all modifications to the operands by the expression, if any

where, for convenience of wording, its "operands" refer to its largest sub-expressions that consist of an id-expression or invocations of `std::move`, `std::forward`, and `std::declval`.

The cv-qualification and value category of each operand is determined by assuming that each template type parameter in its type denotes a cv-unqualified complete non-array object type.

Every expression required to be equality preserving is further required to be stable, that is, two evaluations of it with the same input objects must have equal outputs without any explicit intervening modification of those input objects.

Unless noted otherwise, every expression used in a `requires` expression of the standard library concepts is required to be equality preserving, and the evaluation of the expression may modify only its non-constant operands. Operands that are constant must not be modified.

In the standard library, the following concepts are allowed to have non equality-preserving `requires` expressions:

- `output_iterator`
- `indirectly_writable`
- `invocable`
- `weakly_incrementable`
- `range`

### Implicit expression variations

A `requires` expression that uses an expression that is non-modifying for some constant lvalue operand also implicitly requires additional variations of that expression that accept a non-constant lvalue or (possibly constant) rvalue for the given operand unless such an expression variation is explicitly required with differing semantics.

These *implicit expression variations* must meet the same semantic requirements of the declared expression. The extent to which an implementation validates the syntax of the variations is unspecified.

```cpp
template<class T>
concept C = requires(T a, T b, const T c, const T d)
{
    c == d;           // expression #1: does not modify the operands
    a = std::move(b); // expression #2: modifies both operands
    a = c;            // expression #3: modifies the left operand `a`
};

// Expression #1 implicitly requires additional expression variations that
// meet the requirements for c == d (including non-modification),
// as if the following expressions had been declared as well:

// ------ const == const ------- ------ const == non-const ---
//                                         c  ==           b;
//            c == std::move(d);           c  == std::move(b);
// std::move(c) ==           d;  std::move(c) ==           b;
// std::move(c) == std::move(d); std::move(c) == std::move(b);

// -- non-const == const ------- -- non-const == non-const ---
//           a  ==           d;            a  ==           b;
//           a  == std::move(d);           a  == std::move(b);
// std::move(a) ==           d;  std::move(a) ==           b;
// std::move(a) == std::move(d); std::move(a) == std::move(b);

// Expression #3 implicitly requires additional expression variations that
// meet the requirements for a = c
// (including non-modification of the second operand),
// as if the expressions a = b (non-constant lvalue variation)
// and a = std::move(c) (const rvalue variation) had been declared.

// Note: Since expression #2 already requires the non-constant rvalue variation
// (a == std::move(b)) explicitly, expression #3 does not implicitly require it anymore.

// The type T meets the explicitly stated syntactic requirements of
// concept C above, but does not meet the additional implicit requirements
// (i.e., T satisfies but does not model C):
// a program requires C<T> is ill-formed (no diagnostic required).
struct T
{
    bool operator==(const T&) const { return true; }
    bool operator==(T&) = delete;
};
```

### Standard library concepts

Defined in namespace `std`

**Core language concepts**

Defined in header `<concepts>`

- `same_as` (C++20): specifies that a type is the same as another type (concept)
- `derived_from` (C++20): specifies that a type is derived from another type (concept)
- `convertible_to` (C++20): specifies that a type is implicitly convertible to another type (concept)
- `common_reference_with` (C++20): specifies that two types share a common reference type (concept)
- `common_with` (C++20): specifies that two types share a common type (concept)
- `integral` (C++20): specifies that a type is an integral type (concept)
- `signed_integral` (C++20): specifies that a type is an integral type that is signed (concept)
- `unsigned_integral` (C++20): specifies that a type is an integral type that is unsigned (concept)
- `floating_point` (C++20): specifies that a type is a floating-point type (concept)
- `assignable_from` (C++20): specifies that a type is assignable from another type (concept)
- `swappable` (C++20), `swappable_with`: specifies that a type can be swapped or that two types can be swapped with each other (concept)
- `destructible` (C++20): specifies that an object of the type can be destroyed (concept)
- `constructible_from` (C++20): specifies that a variable of the type can be constructed from or bound to a set of argument types (concept)
- `default_initializable` (C++20): specifies that an object of a type can be default constructed (concept)
- `move_constructible` (C++20): specifies that an object of a type can be move constructed (concept)
- `copy_constructible` (C++20): specifies that an object of a type can be copy constructed and move constructed (concept)

**Comparison concepts**

Defined in header `<concepts>`

- `boolean-testable` (C++20): specifies that a type can be used in Boolean contexts (exposition-only concept*)
- `equality_comparable` (C++20), `equality_comparable_with`: specifies that operator `==` is an equivalence relation (concept)
- `totally_ordered` (C++20), `totally_ordered_with`: specifies that the comparison operators on the type yield a total order (concept)

Defined in header `<compare>`

- `three_way_comparable` (C++20), `three_way_comparable_with`: specifies that operator `<=>` produces consistent result on given types (concept)

**Object concepts**

Defined in header `<concepts>`

- `movable` (C++20): specifies that an object of a type can be moved and swapped (concept)
- `copyable` (C++20): specifies that an object of a type can be copied, moved, and swapped (concept)
- `semiregular` (C++20): specifies that an object of a type can be copied, moved, swapped, and default constructed (concept)
- `regular` (C++20): specifies that a type is regular, that is, it is both `semiregular` and `equality_comparable` (concept)

**Callable concepts**

Defined in header `<concepts>`

- `invocable` (C++20), `regular_invocable`: specifies that a callable type can be invoked with a given set of argument types (concept)
- `predicate` (C++20): specifies that a callable type is a Boolean predicate (concept)
- `relation` (C++20): specifies that a callable type is a binary relation (concept)
- `equivalence_relation` (C++20): specifies that a `relation` imposes an equivalence relation (concept)
- `strict_weak_order` (C++20): specifies that a `relation` imposes a strict weak ordering (concept)

Additional concepts can be found in the iterators library, the algorithms library, and the ranges library.

### See also

- [Named Requirements](https://en.cppreference.com/w/cpp/named_req)

## 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/concepts (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.