Defining the == Operator

Why do we need to explicitly define the == operator if we already have <=>?

The == operator is necessary even if we already have the <=> (spaceship) operator for a couple of reasons. Primarily, it comes down to performance and specific use cases.

Firstly, == is usually more efficient than <=>. When checking for equality, == can directly compare values, often using simpler operations.

On the other hand, <=> has to determine whether one value is less than, equal to, or greater than another, which can involve more complex logic.

For instance, comparing two strings for equality might only require a single operation if their lengths differ, whereas a three-way comparison would need to perform additional checks to determine the ordering.

Secondly, == is semantically clearer in many contexts. When you see == in code, you immediately understand that the check is for equality.

Using <=> for equality checks can make the code less readable and harder to understand at a glance, especially for those who may not be familiar with the spaceship operator.

Here's an example:

#include <compare>
#include <iostream>

class Number {
 public:
  std::strong_ordering operator<=>(
    const Number& Other) const {
    return Value <=> Other.Value;
  }

  bool operator==(const Number& Other) const {
    return Value == Other.Value;
  }

  int Value;
};

int main() {
  Number A{1};
  Number B{2};

  if (A == B) {
    std::cout << "A is equal to B";
  } else {
    std::cout << "A is not equal to B";
  }
}
A is not equal to B

In this example, operator== directly compares the values, while operator<=> handles the three-way comparison. By defining both, we ensure that equality checks are efficient and our intentions in the code are clear.

The Spaceship Operator and Expression Rewriting

A guide to simplifying our comparison operators using C++20 features

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Equality vs. Equivalence
What are the differences between std::strong_ordering::equal and std::strong_ordering::equivalent?
Benefits of the Spaceship Operator
What are the benefits of using the spaceship operator <=> over traditional comparison operators?
Custom Comparison Logic
How can we implement custom comparison logic using the spaceship operator <=>?
Using <=> for Sorting
Can <=> be used for sorting algorithms in C++20?
Niche Cases for Three-Way Comparison
How does the C++20 standard handle types that do not naturally fit into the three-way comparison model?
Real-World Examples of <=>
What are some practical examples of using <=> in real-world applications?
Ask Your Own Question
Temporarily unavailable while we roll out updates. Back in a few days!