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
Linda HamiltonOriginal
2024-11-07 21:11:031097browse

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
};

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

X a, b;

a == b; // OK!

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;
    }
};

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

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:
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