Home > Backend Development > C++ > Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C 20?

Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C 20?

Linda Hamilton
Release: 2024-11-07 21:11:03
Original
1123 people have browsed it

Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C  20? 
` Operator in C 20? " />

Non-defaulted Operator <=> and the Absence of == and !=

In C 20, the spaceship operator <=> provides a general-purpose comparison mechanism. However, a strange behavior arises when using a custom three-way comparison implementation.

Default Implementation Generates == and !=

Consider the following code using the default implementation of <=>:

struct X {
    int Dummy = 0;
    auto operator<=>(const X&amp;) const = default; // Default implementation
};
Copy after login

In this case, the code compiles successfully and allows the use of == and != for comparing instances of X:

X a, b;

a == b; // OK!
Copy after login

Custom Implementation Blocks == and !=

However, when a custom implementation of <=> is provided:

struct X {
    int Dummy = 0;
    auto operator<=>(const X&amp; other) const {
        return Dummy <=> other.Dummy;
    }
};
Copy after login

Compiling results in the error:

error C2676: binary '==': 'X' does not define this operator or a conversion to a type acceptable to the predefined operator
Copy after login

Reason for Behavior

This behavior is intentional. According to the C 20 standard:

If the class definition does not explicitly declare an == operator function, but declares a defaulted three-way comparison function, an == operator function is declared implicitly with the same access as the three-way comparison operator function.

Only a defaulted <=> operator generates a synthesized ==. This is because classes like std::vector should not use a non-defaulted <=> for equality tests, as it may be less efficient than a custom implementation.

Therefore, if a class has a custom <=> implementation, the programmer must also provide a custom == implementation to ensure correct comparison behavior.

The above is the detailed content of Why Can't I Use `==` and `!=` with a Custom `<=>` Operator in C 20?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template