A concept is a named compile-time predicate on types
template <class T> concept C = <constant boolean expression>; defines a predicate. C<int> is a bool known at compile time, and a constrained template is only a candidate when its constraints are satisfied. Three things to keep straight:
- Concepts check syntax, not semantics.
std::totally_ordered<double>is true even thoughNaNbreaks the ordering. The semantic requirements in the standard are promises you make, not things the compiler checks. - Constraints are checked before the body is instantiated, so a failure is reported at the call site in terms of the concept, not deep inside the library.
- When several constrained overloads match, the compiler picks the most constrained one, using a precise rule called subsumption. That rule works only on named concepts, which is the main trap.
All programs below were compiled with Apple clang 17, c++ -std=c++20 -O2 -Wall.
Requires-expressions
A requires (params) { requirements; } expression is true if every requirement is valid for the given types. The parameters are never evaluated; they only give you names to write expressions with. There are four kinds of requirement:
| Kind | Syntax | Satisfied when |
|---|---|---|
| simple | a + b; | the expression compiles |
| type | typename T::value_type; | the type exists |
| compound | { e } -> std::same_as<void>; | e compiles and decltype((e)) satisfies the concept (optionally also noexcept) |
| nested | requires sizeof(T) == 8; | the expression compiles and is true |
The nested form is the one people get wrong: writing sizeof(T) == 8; without requires is a simple requirement and only checks that the comparison compiles, which it always does.
#include <concepts>
#include <cstdint>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
// A concept is a named compile-time predicate on types.
template <class B>
concept OrderBook = requires(B book, const B& cbook, std::int64_t px, std::int64_t qty) {
typename B::price_type; // nested type must exist
{ cbook.best_bid() } -> std::convertible_to<std::int64_t>; // expression valid, result converts
{ cbook.best_ask() } -> std::convertible_to<std::int64_t>;
{ book.add(px, qty) } -> std::same_as<void>;
requires sizeof(typename B::price_type) == 8; // nested requirement: must be true
};
struct MapBook {
using price_type = std::int64_t;
std::map<std::int64_t, std::int64_t> bids, asks;
std::int64_t best_bid() const { return bids.empty() ? 0 : bids.rbegin()->first; }
std::int64_t best_ask() const { return asks.empty() ? 0 : asks.begin()->first; }
void add(std::int64_t px, std::int64_t qty) { (qty > 0 ? bids : asks)[px] += qty > 0 ? qty : -qty; }
};
struct FloatBook { // price_type is 4 bytes
using price_type = float;
std::int64_t best_bid() const { return 0; }
std::int64_t best_ask() const { return 0; }
void add(std::int64_t, std::int64_t) {}
};
static_assert(OrderBook<MapBook>);
static_assert(!OrderBook<FloatBook>);
static_assert(!OrderBook<std::vector<int>>);
// Three ways to write the same constraint.
template <OrderBook B> std::int64_t spread1(const B& b) { return b.best_ask() - b.best_bid(); }
template <class B> requires OrderBook<B> std::int64_t spread2(const B& b) { return b.best_ask() - b.best_bid(); }
std::int64_t spread3(const OrderBook auto& b) { return b.best_ask() - b.best_bid(); }
int main() {
MapBook b;
b.add(10'000, 5); b.add(10'002, -3); b.add(9'999, 7);
std::printf("bid %lld ask %lld spread %lld %lld %lld\n", (long long)b.best_bid(), (long long)b.best_ask(),
(long long)spread1(b), (long long)spread2(b), (long long)spread3(b));
}
bid 10000 ask 10002 spread 2 2 2
The book holds bids at 10000 (5) and 9999 (7) and an ask at 10002 (3), so the best bid is 10000, the best ask 10002, and the spread 2. FloatBook has all the members but fails the nested requirement because float is 4 bytes; std::vector<int> fails at the first line. The static_asserts are the habit to copy: test your concept against types that should pass and types that should fail, because a concept that is accidentally always true compiles silently.
The three declarations of spread are equivalent. The abbreviated form const OrderBook auto& is a shorthand for a constrained template parameter.
Constraining overloads and subsumption
With concepts, overlapping overloads are allowed. When more than one is viable and they are otherwise equally good, the compiler compares their constraints. The constraints are broken into atomic constraints (the leaves that are not &&, || or a concept name), and overload A beats B if A's constraints subsume B's: whenever A's hold, B's must hold by logic alone.
#include <concepts>
#include <cstdio>
template <std::integral T> const char* kind(T) { return "integral"; }
template <std::signed_integral T> const char* kind(T) { return "signed_integral"; } // more constrained
template <class T> const char* kind(T) { return "unconstrained"; }
int main() {
std::printf("%s %s %s\n", kind(1), kind(1u), kind(1.0));
}
signed_integral integral unconstrained
std::signed_integral<T> is defined as std::integral<T> && std::is_signed_v<T>, so it subsumes std::integral<T>, and kind(1) picks it without ambiguity. 1u satisfies only integral; 1.0 satisfies only the unconstrained overload, and a constrained candidate beats an unconstrained one when both match.
Now the trap. Write the same logic with raw type traits:
#include <type_traits>
template <class T> requires std::is_integral_v<T>
const char* kind(T) { return "integral"; }
template <class T> requires (std::is_integral_v<T> && std::is_signed_v<T>)
const char* kind(T) { return "signed integral"; }
int main() { return kind(1)[0]; }
Clang:
subsume_bad.cpp:6:21: error: call to 'kind' is ambiguous
subsume_bad.cpp:3:13: note: candidate function [with T = int]
subsume_bad.cpp:5:13: note: candidate function [with T = int]
subsume_bad.cpp:2:29: note: similar constraint expressions not considered equivalent; constraint expressions cannot be considered equivalent unless they originate from the same concept
Two atomic constraints are the same only if they come from the same expression in the source, which in practice means the same concept. The two std::is_integral_v<T> expressions are written in different places, so the compiler does not treat one as implying the other. The fix is to name the pieces:
#include <cstdio>
#include <type_traits>
template <class T> concept Integral = std::is_integral_v<T>;
template <class T> concept SignedIntegral = Integral<T> && std::is_signed_v<T>;
template <Integral T> const char* kind(T) { return "integral"; }
template <SignedIntegral T> const char* kind(T) { return "signed integral"; }
int main() { std::printf("%s %s\n", kind(1), kind(1u)); }
signed integral integral
The standard concepts
<concepts>, <iterator> and <ranges> define the vocabulary. The ones worth knowing by name:
| Concept | Means |
|---|---|
std::same_as<T, U>, std::convertible_to<From, To>, std::derived_from<D, B> | type relationships |
std::integral, std::signed_integral, std::floating_point | arithmetic categories |
std::movable, std::copyable, std::semiregular, std::regular | object semantics (regular = copyable, default constructible, equality comparable) |
std::equality_comparable, std::totally_ordered | comparison operators exist |
std::invocable<F, Args...>, std::predicate<F, Args...> | callables |
std::ranges::range, std::ranges::random_access_range, std::random_access_iterator | ranges and iterators |
#include <concepts>
#include <cstdio>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <ranges>
#include <string>
#include <vector>
struct Fill { long px, qty; };
static_assert(std::regular<int> && std::regular<std::string>);
static_assert(!std::copyable<std::unique_ptr<int>> && std::movable<std::unique_ptr<int>>);
static_assert(std::totally_ordered<double>); // syntax only: NaN still breaks the ordering
static_assert(std::ranges::random_access_range<std::vector<int>>);
static_assert(!std::ranges::random_access_range<std::list<int>>);
static_assert(std::invocable<void (*)(const Fill&), Fill&>);
template <class T>
struct Ring {
std::vector<T> buf;
// A non-template member constrained on the class parameter: it exists only for some T.
T sum() const requires std::integral<T> || std::floating_point<T> {
T s{};
for (const T& x : buf) s += x;
return s;
}
};
template <std::invocable<const Fill&> F>
void for_each_fill(const std::vector<Fill>& fills, F&& on_fill) {
for (const Fill& f : fills) std::invoke(on_fill, f);
}
int main() {
Ring<long> r{{1, 2, 3}};
Ring<std::string> names{{"a", "b"}}; // fine: sum() is never called
std::printf("sum %ld, names %zu\n", r.sum(), names.buf.size());
long notional = 0;
for_each_fill({{100, 5}, {101, 2}}, [&](const Fill& f) { notional += f.px * f.qty; });
std::printf("notional %ld\n", notional);
}
sum 6, names 2
notional 702
Two features here have no clean SFINAE equivalent. Ring<T>::sum is not a template, yet it carries a requires clause on the class's T: Ring<std::string> is a valid type and only a call to sum() on it would fail. And std::invocable<const Fill&> F documents and checks the callback's signature at the call site (here ).
Error messages you can read
The classic demonstration: sort a std::list, whose iterators are bidirectional, not random access.
std::list<int> l{3, 1, 2};
std::sort(l.begin(), l.end()); // unconstrained (C++98 interface)
std::ranges::sort(l); // constrained with concepts
With Apple clang 17 and libc++, the std::sort version produced 188 lines with 5 errors, all inside make_heap.h, partial_sort.h, sort_heap.h and sort.h ("invalid operands to binary expression"), because the template is instantiated and fails where it first subtracts two iterators. The std::ranges::sort version produced 22 lines and 1 error, and the notes read as a proof:
note: candidate template ignored: constraints not satisfied [with _Range = std::list<int> &, ...]
note: because 'std::list<int> &' does not satisfy 'random_access_range'
note: because 'iterator_t<list<int, allocator<int>> &>' (aka 'std::__list_iterator<int, void *>') does not satisfy 'random_access_iterator'
note: because 'derived_from<_ITER_CONCEPT<__list_iterator<int, void *> >, random_access_iterator_tag>' evaluated to false
(Lines abridged to the notes; the file paths are libc++ headers.) Constraining your own templates gives your users the same experience.
Worked example
a Price concept that rejects bool and char
A pricing helper should accept fixed-point tick counts (signed integers of at least 32 bits) and floating-point prices, but reject bool, char, short and unsigned types, all of which std::is_arithmetic accepts. Write the concept and the tests that prove it.
Show solutionHide solution
Start from the standard concepts and add the one extra condition:
template <class T>
concept Price = (std::signed_integral<T> && sizeof(T) >= 4) || std::floating_point<T>;
static_assert(Price<std::int64_t> && Price<int> && Price<double>);
static_assert(!Price<bool> && !Price<char> && !Price<short> && !Price<unsigned>);
Why each rejection happens:
boolis integral butstd::is_signed_v<bool>is false, sostd::signed_integral<bool>fails.charis signed on Apple arm64 (and on x86-64 Linux), sosigned_integral<char>is true; it is thesizeof(T) >= 4condition that rejects it. On a platform wherecharis unsigned it would fail earlier, which is why the size test is there and why both cases are pinned bystatic_assert.shortis 2 bytes;unsignedis not signed.
Both assertions compile with Apple clang 17. Note that the size test is inside the concept definition, a plain boolean expression; inside a requires-expression it would have to be written as the nested requirement requires sizeof(T) >= 4;.
Knowledge check
Inside a requires-expression, a concept author writes the line: sizeof(T) == 8; What does it require?
Knowledge check
Two overloads are constrained with requires std::is_integral_v<T> and requires (std::is_integral_v<T> && std::is_signed_v<T>). What happens on a call with an int?
Knowledge check
std::totally_ordered<double> is true. What does that tell you about sorting a vector<double> that contains NaN?
Key takeaways
- A requires-expression has simple, type, compound and nested requirements; only the nested form checks that a condition is true.
- Test concepts with
static_asserton types that should pass and types that should fail. - Overloads are ordered by subsumption, which only recognises shared named concepts; raw traits in separate clauses give ambiguity.
- Use the standard concepts (
std::integral,std::regular,std::invocable,std::ranges::random_access_range) as building blocks. - Concepts check syntax, not semantics, and they turn deep instantiation errors into short "because ... does not satisfy ..." chains.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).