Creating Custom Concepts

Difference between requires keyword and requires expression

What is the difference between the requires keyword and a requires expression in C++20 concepts?

Abstract art representing computer hardware

The requires keyword and requires expressions serve different purposes in C++20 concepts:

The requires keyword is used within a requires expression to assert that a specific expression must be valid and evaluate to true for a type to satisfy the concept. For example:

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

Here, the requires keyword is used to assert that T must be an arithmetic type and that the expression a + b must be valid.

A requires expression, on the other hand, is a way to group multiple requirements together. It consists of a parameter list and a body containing one or more requirements. A type satisfies the requires expression if all the requirements in its body are met. For example:

template <typename T>
concept Printable = requires(T a) {
  std::cout << a;
};

In this case, the requires expression states that for a type T to be Printable, the expression std::cout << a must be valid, where a is an instance of type T.

So, in summary, the requires keyword is used within a requires expression to assert individual requirements, while a requires expression is a way to group and define a set of requirements that a type must satisfy to meet a concept.

This Question is from the Lesson:

Creating Custom Concepts

Learn how to create your own C++20 concepts to define precise requirements for types, using boolean expressions and requires statements.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Creating Custom Concepts

Learn how to create your own C++20 concepts to define precise requirements for types, using boolean expressions and requires statements.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved