Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 171 ยท Templates and Generic Programming

Concepts and Constraints

Learn C++20 concepts - requires clauses, standard concepts like std::integral and std::ranges::range, writing your own concepts, and much clearer template errors.

A plain template accepts any type and only discovers a problem deep inside its body, often producing pages of errors about code you never wrote. Before C++20, the requirements on a template parameter lived only in comments ("T must be comparable") and in clever tricks that were hard to read. Concepts make those requirements part of the code: a concept is a named, compile-time predicate on types, and a constraint attaches it to a template.

With constraints, sort(my_list) fails with a short message saying the argument doesn't satisfy random_access_range, instead of a wall of text from inside the algorithm. Constraints also let you write overloads that are chosen by what a type can do: one version for integers, another for floating-point numbers, another for anything iterable. In this lesson you'll use the standard concepts, learn the four ways to write a constraint, write your own concepts with requires expressions, and see how the compiler picks the most constrained overload. You should already know function templates and class templates.

Constraining a template

The simplest constraint replaces typename with a concept name. Here std::integral (from <concepts>) accepts only integer types: int, long, char, bool, unsigned, and so on.

C++ A constrained function template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Uncomment the last line and press Run. GCC reports no matching function for call to 'gcd(double, double)', then constraints not satisfied, and finally that is_integral_v<_Tp> with _Tp = double evaluated to false. Without the constraint, you'd instead get an error about % on double from inside the function body. With a one-line example that's not much worse, but in a real library the body may be hundreds of lines deep in helper templates.

Constraints are checked before the body is instantiated, as part of overload resolution. A template whose constraints aren't satisfied simply isn't a candidate.

Four ways to write a constraint

All four forms below mean the same thing for a single parameter. Pick the one that reads best.

C++
#include <concepts>

// 1. Type-constraint in the template parameter list
template <std::integral T>
T twice1(T x) { return x * 2; }

// 2. requires clause after the template parameter list
template <typename T>
    requires std::integral<T>
T twice2(T x) { return x * 2; }

// 3. Trailing requires clause after the function declarator
template <typename T>
T twice3(T x) requires std::integral<T> { return x * 2; }

// 4. Abbreviated function template with a constrained auto parameter
auto twice4(std::integral auto x) { return x * 2; }

The requires clause forms (2 and 3) accept any compile-time bool expression built from concepts and type traits, combined with &&, || and !. That's how you express constraints that involve several parameters, or alternatives:

C++
template <typename T, typename U>
    requires std::integral<T> && std::integral<U>
auto add(T a, U b) { return a + b; }

template <typename T>
    requires std::integral<T> || std::floating_point<T>
T half(T x) { return x / 2; }

Form 4 is the shortest for simple functions; each auto parameter is a separate template parameter, so void f(std::integral auto a, std::integral auto b) allows a and b to have different types. You can also constrain a deduced variable: std::integral auto n = compute(); fails to compile if compute() returns a double.

The standard concepts

The standard library ships with dozens of concepts. These are the ones you'll use most:

Header Concept Satisfied when
<concepts> std::integral<T>, std::signed_integral<T>, std::unsigned_integral<T> T is an integer type (of that signedness)
<concepts> std::floating_point<T> T is float, double or long double
<concepts> std::same_as<T, U> T and U are the same type
<concepts> std::convertible_to<From, To> From converts implicitly to To
<concepts> std::derived_from<D, B> D publicly derives from B
<concepts> std::equality_comparable<T> a == b and a != b work
<concepts> std::totally_ordered<T> ==, !=, <, >, <=, >= all work
<concepts> std::copyable<T>, std::movable<T>, std::regular<T> T can be copied / moved / behaves like a value
<concepts> std::invocable<F, Args...>, std::predicate<F, Args...> F can be called with Args (returning something bool-like)
<ranges> std::ranges::range<R> R has begin and end
<ranges> std::ranges::random_access_range<R>, std::ranges::sized_range<R> R supports indexing-like access / knows its size
<iterator> std::input_iterator<I>, std::random_access_iterator<I> I is an iterator of that category

Since a concept is just a compile-time bool, you can test it directly. That's a great way to explore what they mean:

C++ Asking concepts about types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that std::unique_ptr<int> is movable but not copyable, and that a std::list is a range but not a random-access range, which is exactly why std::ranges::sort refuses a list.

Overloading on constraints

When several constrained overloads could handle a call, the compiler picks the most constrained one: the one whose constraints imply the others'. This replaces most of the old tag-dispatch and enable_if tricks with readable code.

C++ The most constrained overload wins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Why is signed_integral "more constrained" than integral? Because the standard defines signed_integral<T> as integral<T> && is_signed_v<T>. The compiler breaks each concept into its parts (its atomic constraints) and sees that one conjunction contains the other. This subsumption only works through concept names: if you write the raw expression std::is_integral_v<T> && std::is_signed_v<T> in two places, the compiler won't treat them as related, and the call may be ambiguous. Build your constraints out of named concepts.

Writing your own concepts

A concept definition is a template that produces a bool:

C++
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;

For requirements that aren't covered by existing concepts, use a requires expression. It lists operations that must compile, without ever running them:

C++
template <typename T>
concept Shape = requires(const T& s) {
    s.area();                                          // simple requirement: must compile
    { s.area() } -> std::convertible_to<double>;       // compound: and result converts to double
    { s.name() } noexcept -> std::same_as<std::string>;// must be noexcept, exact type
    typename T::Unit;                                  // type requirement: nested type exists
    requires sizeof(T) <= 64;                          // nested requirement: a bool that must be true
};

The parameters after requires (here const T& s) are imaginary objects you can use in expressions; nothing is constructed. The -> concept part after braces applies the concept to the expression's type, so { s.area() } -> std::convertible_to<double> means std::convertible_to<decltype((s.area())), double>.

C++ A custom concept with a requires expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

static_assert(Shape<Circle>) is a cheap and valuable habit: it documents that your type is meant to model the concept, and it fails right at the type's definition if someone later breaks that. Try uncommenting report(Label{}) to see an error that points at the missing s.area() requirement.

Notice that Shape is satisfied by any type with the right members. There's no base class and no virtual call: this is static polymorphism. Compare it with abstract classes, where the choice of function happens at run time through a vtable. Concepts are a better fit when the type is known at compile time and you want zero overhead; virtual functions are needed when you must store mixed types in one container.

Constraining class templates and members

Class templates take constraints the same way, and individual members can have their own trailing requires clauses. A member whose constraint fails just doesn't exist for that instantiation.

C++ A constrained class template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

HasSum asks "would v.sum() compile for this type?" and turns the answer into a bool instead of an error. That only works where the expression depends on a template parameter (inside a concept or a template). Outside templates, an invalid expression in a requires expression is a hard error. Inside a template, it's a quick way to adapt to a type's abilities: if constexpr (requires { x.size(); }) { ... }.

Pitfalls and good habits

  • Concepts check syntax, not meaning. Shape checks that area() exists and returns something double-like; it can't check that the value is actually an area. Document the semantic expectations next to the concept.
  • Don't over-constrain. Require what the body actually uses. template <std::integral T> on a function that would also work for double makes it less useful.
  • Don't under-constrain either. A constraint that's weaker than the body's needs moves the error back inside the template, losing the benefit.
  • Prefer standard concepts (std::totally_ordered, std::invocable, std::ranges::range) over home-grown equivalents; everyone knows what they mean, and they subsume correctly.
  • Name your concepts after capabilities: Shape, Hashable, Drawable. They read like adjectives or nouns in a sentence: template <Drawable T>.
  • Concepts can't be specialized or constrained themselves, and they can't be recursive.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given template <std::integral T> T twice(T x), what happens with twice(2.5)?

    Constraints are checked during overload resolution. T is deduced as double, std::integral<double> is false, so the template is not a candidate and there is no matching function.
  2. 2. Overloads take std::integral auto and std::signed_integral auto. Which runs for describe(-5)?

    std::signed_integral is defined in terms of std::integral plus an extra condition, so it subsumes integral and is the better match for int.
  3. 3. In concept Shape = requires(const T& s) { { s.area() } -> std::convertible_to<double>; };, what does the requires expression do with s?

    Requires expressions are unevaluated. The parameter s is a placeholder used to describe expressions that must be valid.
  4. 4. Why is std::ranges::sort rejected for a std::list<int>?

    std::ranges::sort requires random-access iterators. A list only has bidirectional iterators, so the constraint fails; use the member list::sort() instead.
  5. 5. With concept HasSum = requires(const V& v) { v.sum(); };, what does std::println("{}", HasSum<SortedVector<std::string>>); print if sum() is constrained to numbers?

    A concept is a compile-time bool. When the required expression would be invalid for the type, the concept is simply false instead of an error.

Summary

  • A concept is a named compile-time predicate on types; a constraint attaches it to a template so unsuitable types are rejected up front with clear errors.
  • Write constraints as template <std::integral T>, a requires clause, a trailing requires, or std::integral auto parameters.
  • The standard concepts in <concepts>, <iterator> and <ranges> cover numbers, comparison, copying, callables, iterators and ranges.
  • Among matching overloads the most constrained one wins, via subsumption, which only works through named concepts.
  • Define your own with concept Name = ...; and requires (params) { ... } expressions with simple, compound, type and nested requirements.
  • Constrain class templates and individual members; use static_assert(Concept<Type>) to document and check that a type models a concept.

Next: Variadic Templates and Fold Expressions, where templates take any number of arguments.