Using Concepts with Classes

Requiring Equality Operator

How can I ensure a class has a proper equality operator using concepts?

Abstract art representing computer hardware

You can create a concept that requires a class to have a properly defined equality operator (operator==). Here's an example:

#include <concepts>

template <typename T>
concept EqualityComparable =
  requires(T a, T b) {
    { a == b } -> std::convertible_to<bool>;
    { a != b } -> std::convertible_to<bool>;
};

class Player {
 public:
  int Score;

  bool operator==(const Player& other) const {
    return Score == other.Score; }

  bool operator!=(const Player& other) const {
    return !(*this == other); }
};

// Passes
static_assert(EqualityComparable<Player>);

The EqualityComparable concept checks if a type T has the equality operators == and != defined.

The requirements { a == b } -> std::convertible_to<bool> and { a != b } -> std::convertible_to<bool> specify that the expressions a == b and a != b should be convertible to bool, where a and b are instances of type T.

In the Player class, we define operator== to compare the Score members, and operator!= to negate the result of operator==.

The static_assert at the end verifies that Player satisfies the EqualityComparable concept.

Note that the standard library already provides the std::equality_comparable concept, which you can use directly instead of defining your own:

static_assert(std::equality_comparable<Player>);
This Question is from the Lesson:

Using Concepts with Classes

Learn how to use concepts to express constraints on classes, ensuring they have particular members, methods, and operators.

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

This Question is from the Lesson:

Using Concepts with Classes

Learn how to use concepts to express constraints on classes, ensuring they have particular members, methods, and operators.

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:

  • 125 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