`requires` — C++ Keyword
`requires` — C++ Keyword
The requires keyword in C++20: introduces constraints on templates or checks expressions at compile time.
`requires` — C++ Keyword
The requires keyword in C++20: introduces constraints on templates or checks expressions at compile time.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
requiresHas two related uses in C++20: (1) a requires-clause that constrains a template or function, and (2) a requires-expression that tests whether expressions are well-formed.
// Requires-clause: constrains the template
template <typename T> requires Constraint<T>
void func(T);
// Requires-expression: evaluates to bool
requires (T a) {
{ a + a } -> std::same_as<T>;
a.size();
}
#include <concepts>
#include <print>
template <typename T>
concept Addable = requires(T a, T b) {
{ a + b } -> std::convertible_to<T>;
};
template <Addable T>
T sum(T a, T b) {
return a + b;
}
// Inline requires-clause
template <typename T>
requires std::integral<T>
T next(T n) { return n + 1; }
int main() {
std::println("{}", sum(3, 4)); // 7
std::println("{:.1f}", sum(1.1, 2.2)); // 3.3
std::println("{}", next(41)); // 42
}
true if every requirement in its body is satisfied and false otherwise — it never causes a hard error.&& and || create conjunctions and disjunctions.requiresint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}