Search⌘ K

Requires Expressions

Explore how requires expressions enable you to define reusable and self-explanatory concepts in C++20. Understand the syntax and types of requirements, including simple, type, compound, and nested, to enhance your template programming skills and enforce type safety effectively.

Thanks to requires expressions, you can define powerful concepts. A requires expression has the following form:

requires (parameter-list(optional)) {requirement-seq}
  • parameter-list: A comma-separated list of parameters, such as in a function declaration
  • requirement-seq: A sequence of requirements, consisting of simple, type, compound, or nested requirements

Let’s discuss its type one by one.

Simple requirements

The following concept Addable is a simple requirement:

template <typename T>
concept Addable = requires (T a, T b) {
    a + b; 
};

The concept Addable requires that the addition a + b of two values of the same type T is possible.

🔑 Avoid anonymous concepts: ...