In C++20, how do you define a concept and constrain a function template with it, and what does a caller see on misuse?
answer
- a named compile-time predicate
- template<class T> concept Name = ...
- requires-clause, type-constraint, constrained auto
- constraints not satisfied, because...
basics
~20 sWrite template<class T> concept Name = a bool constraint expression; then apply it with a requires-clause, as a type-constraint such as template<Name T>, or as Name auto in a parameter. A failing call reports which concept was not satisfied.
solid answer
~40 sA C++20 concept is a named compile-time predicate on template arguments: `template <class T> concept Arithmetic = std::integral<T> || std::floating_point<T>;`. You apply it in a **requires-clause** (`template <class T> requires Arithmetic<T>`), as a **type-constraint** (`template <Arithmetic T>`), or in an abbreviated function template (`auto half(Arithmetic auto x)`), which is still a template. The constraint is checked during overload resolution, so an unsatisfied overload is not viable and drops out; when nothing remains, the error names the concept. Apple clang 21 prints `constraints not satisfied`, then `because 'std::vector<int>' does not satisfy 'Arithmetic'` and which part failed. A concept-id such as `Arithmetic<int>` is a `bool` constant usable in `static_assert`. A concept cannot be specialized and cannot carry its own constraints.
code
cpp · 21 lines#include <concepts>
#include <iostream>
#include <vector>
// A concept: a named, reusable compile-time predicate on types.
template <class T>
concept Arithmetic = std::integral<T> || std::floating_point<T>;
// Three ways to apply the same constraint.
template <class T> requires Arithmetic<T>
T mean_a(const std::vector<T>& v) { T s{}; for (T x : v) s += x; return s / T(v.size()); }
template <Arithmetic T>
T mean_b(const std::vector<T>& v) { return mean_a(v); }
auto half(Arithmetic auto x) { return x / 2; } // abbreviated function template
int main() {
std::cout << mean_b(std::vector<double>{1, 2, 4}) << ' ' << half(9) << '\n';
// half(std::vector<int>{}); // error: constraints not satisfied
}go deeper
Recognise template<Concept T> and Concept auto as constrained templates, and know that std::integral and std::floating_point come from the concepts header.
Write a concept from standard concepts, apply it in all three forms, and read the constraints-not-satisfied diagnostic down to the failing piece.
Separate constraints that steer overload resolution from static_asserts that only reject, and explain satisfaction versus modeling for library concepts.
Decide which requirements a public API names as concepts, and keep those names stable, since callers and other overloads come to depend on them.
## What a concept is A **concept** (C++20) is a named, reusable predicate on template arguments, evaluated entirely at compile time: ```cpp template <class T> concept Arithmetic = std::integral<T> || std::floating_point<T>; ``` The right-hand side is a **constraint-expression**: a `bool` constant expression built from other concepts, type traits and requires-expressions, joined with `&&` and `||`. Naming the concept with arguments, `Arithmetic<double>`, forms a **concept-id**, which is a prvalue of type `bool`. It can appear in `static_assert`, in `if constexpr`, or anywhere a constant is expected. The standard library ships concepts in `<concepts>` (`std::integral`, `std::floating_point`, `std::same_as`, `std::convertible_to`, `std::regular`), in `<iterator>` and in `<ranges>` (`std::ranges::range`). `std::integral<T>` is defined simply as `is_integral_v<T>`. ## Four ways to apply it A numeric algorithms library migrating to C++20 can constrain `mean` in any of these forms; they all attach the same constraint: | Form | Example | |---|---| | requires-clause after the template head | `template <class T> requires Arithmetic<T> T mean(const std::vector<T>&);` | | trailing requires-clause | `template <class T> T mean(const std::vector<T>&) requires Arithmetic<T>;` | | type-constraint on the parameter | `template <Arithmetic T> T mean(const std::vector<T>&);` | | constrained `auto` parameter | `auto half(Arithmetic auto x);` | The last form is an **abbreviated function template**: each `auto` parameter invents a template parameter, so `half` is a template exactly like the others. The same `Concept auto` syntax constrains a deduced variable, `std::integral auto n = count();`, which fails to compile if the deduced type does not satisfy the concept. ## What misuse looks like Constraints are checked when the compiler considers a candidate: after deducing the template arguments, it substitutes them into the constraint and checks that it is **satisfied**. An unsatisfied candidate is not viable. If nothing viable remains, the diagnostic explains the chain. For `half(std::vector<int>{})` Apple clang 21 prints: ```plaintext error: no matching function for call to 'half' note: candidate template ignored: constraints not satisfied [with x:auto = std::vector<int>] note: because 'std::vector<int>' does not satisfy 'Arithmetic' note: because 'std::vector<int>' does not satisfy 'integral' note: and 'std::vector<int>' does not satisfy 'floating_point' ``` That is the main practical gain over `std::enable_if`: the requirement has a name, and the error says which named requirement failed, at the call site, before the body is instantiated. ## Rules about concepts themselves - A concept **cannot be constrained**: it may not have a requires-clause of its own. - A concept is **never instantiated**, so it cannot be explicitly instantiated, explicitly specialized or partially specialized. To change the answer for a type, change the traits or operations the concept checks. - A concept cannot refer to itself; recursion goes through traits instead. - Satisfaction is **syntactic**. The compiler checks that the expressions compile and the constant parts are `true`. The standard library's concepts also carry **semantic requirements**; a type *models* a concept only if it satisfies it and meets those, and using a library facility with a type that satisfies but does not model its constraints makes the program ill-formed, no diagnostic required. ## Constraining a member of a class template A requires-clause can also go on a **non-template member function** of a class template, something `std::enable_if` could never do without turning the member into a template of its own: ```cpp template <class T> struct Stat { T value; void round_in_place() requires std::floating_point<T> { value = std::round(value); } }; ``` `Stat<int>` still instantiates normally; the constraint is checked only when someone names `round_in_place` on it. Apple clang 21 then reports `invalid reference to function 'round_in_place': constraints not satisfied` with `because 'int' does not satisfy 'floating_point'`. The same mechanism lets a class template offer an operation, a constructor or even a special member function only for some of its arguments. ## Where the check sits - **In a constraint**, failure removes the overload: the template is never instantiated for that type, and another overload can win. - **In a `static_assert(Arithmetic<T>)` in the body**, failure is a hard error after the template has already been chosen; it constrains nothing. - **In a class template**, `template <Arithmetic T> class Stats;` rejects `Stats<std::string>` at the point of naming it. For the library, that means each public algorithm states its requirements in its declaration, where both the compiler and the reader see them.
- What is the difference between satisfying and modeling a standard library concept?A type **satisfies** a concept when its constraint expression is true; that is all the compiler checks. It **models** the concept when it also meets the semantic requirements written in the standard, such as `==` being an equivalence relation for `std::equality_comparable`. Passing a type that satisfies but does not model a library function's constraints makes the program ill-formed, no diagnostic required.
- Can you use a concept outside a template's declaration?Yes. A concept-id is a `bool` constant, so `static_assert(Arithmetic<long>);` works anywhere, and `if constexpr (std::integral<T>)` branches on it inside a template. `std::integral auto n = parse();` constrains a deduced variable: if the initializer's type does not satisfy the concept, the declaration does not compile.
- A concept is a kind of class template that you can specialize per type.
- static_assert(Concept<T>) in the body constrains overload resolution like a requires-clause.
- Concepts add run-time checks to the generated code.
- A function with an Arithmetic auto parameter is an ordinary non-template function.
- The compiler verifies that a type's operations behave correctly, not just that they compile.
Assumes C++20 or later: concepts, requires-clauses and constrained auto parameters are C++20 features.