operator== on C++ structs with conversion operators

I’m trying to understand the set of == operators that are explored when comparing two structs where there is no operator == defined. In this case the built-in operator for ints is used for conversion. However this does not work for nested classes for example, i.e. if Y contained a class that defined an == operator. Is this only applicable when a struct can be converted to a built-in type unambiguously?

struct X {
    int x;
};

struct Y {
    int y;
    operator int() {
        return y;
    }
};

int main() {
//    bool val {X{} == X{}}; // does not compile
    bool val {Y{} == Y{}}; // works
}

>Solution :

Classes and structs don’t have equality (or any) operators by default. You need to overload whatever is needed for your implementation and specify the comparisons explicitly.

struct X {
    int x;

    bool operator==(const X& other) const { return x == other.x; }
    bool operator!=(const X& other) const { return y != other.x; }
    ...

};

That’s true for every comparison operator (==, !=, <, >, <=, >=). That is unless you use C++20, in which you can specify the default <=> operator and have the compiler generate them for you (ofc the more members your struct has, the more complicated this gets; the docs on comparisons are a good read).

#include <compare>

struct X {
    int x;

    auto operator<=>(const X&) const = default;
};

Leave a Reply