Search⌘ K
AI Features

The <requires> Clause

Explore how the requires clause in C++20 Concepts allows you to enforce type constraints on template parameters. Understand how to use it between template lists and return types, manage multiple template types, and write clear constraints for safer, more flexible generic functions.

How to write aq requires clause?

In the first way, we use the required clause between the template parameter list and the function return type, which is auto in this case.

C++
#include <concepts>
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;
template <typename T>
requires Number<T>
auto add(T a, T b) {
return a+b;
}

Note how we use the concept and define our constraint in the requires clause that any T template parameter must satisfy the requirements of the concept Number. In order to determine the return type we simply use auto type deduction, but we could use T here as well. However, auto gives us more ...