Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading