Creating Custom Concepts

Negating requires expressions in C++20 concepts

How can I negate a requires expression in a C++20 concept to specify that a type should not satisfy certain requirements?

Abstract art representing computer hardware

In C++20 concepts, you can negate a requires expression using the ! operator to specify that a type should not satisfy certain requirements. This is useful when you want to enforce that a type does not have a particular property or does not support a specific operation.

Here's an example that demonstrates negating a requires expression:

#include <concepts>
#include <iostream>

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

template <NotAddable T>
void add(T a, T b) {
  std::cout << "Cannot add values of this type\n";
}

template <typename T>
void add(T a, T b) {
  std::cout << "Result: " << a + b << '\n';
}

int main() {
  add(1, 2);
  add("Hello", " world");
}
Result: 3
Cannot add values of this type

In this example, the NotAddable concept is defined using a negated requires expression. It specifies that a type T satisfies the concept if the expression a + b is not valid for instances a and b of type T.

The first overload of the add function is constrained by the NotAddable concept, so it will be called when the provided type does not support the + operator. The second overload is unconstrained and will be called for types that do support the + operator.

As you can see, the negated requires expression allows us to specify that a type should not satisfy certain requirements, providing a way to handle types that do not support specific operations or have certain properties.

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