Spaceship simplifications


I ended the last post by stating that I would provide an example of how you can implement the new C++ spaceship operator for your own class. In this post I will show you how that can be done and how it can simplify your implementation a lot.

Assume that you have defined your own type and you want to implement all six different comparison operators. Using C++ 17 this may look something like this:

// Before C++20
class CustomType {
    int value;
public:
    CustomType(int value) : value{ value } {}
    friend bool operator==(const CustomType&, const CustomType&);
    friend bool operator!=(const CustomType&, const CustomType&);
    friend bool operator>(const CustomType&, const CustomType&);
    friend bool operator<(const CustomType&, const CustomType&);
    friend bool operator>=(const CustomType&, const CustomType&);
    friend bool operator<=(const CustomType&, const CustomType&);
};

bool operator==(const CustomType& l, const CustomType& r) {
    return l.value == r.value;
}

bool operator!=(const CustomType& l, const CustomType& r) {
    return l.value != r.value;
}

bool operator>(const CustomType& l, const CustomType& r) {
    return l.value > r.value;
}

bool operator<(const CustomType& l, const CustomType& r) {
    return l.value < r.value;
}

bool operator>=(const CustomType& l, const CustomType& r) {
    return l.value >= r.value;
}

bool operator<=(const CustomType& l, const CustomType& r) {
    return l.value <= r.value;
}

With C++20 and the new spaceship operator the code above can be replaced by this:

// With C++20
class CustomType {
    int value;
public:
    CustomType(int value) : value{ value } {}
    auto operator<=>(const CustomType& other) const = default;
};

That’s it, promise! Quite a lot simpler right?

However, using default only works as long as you want to compare all the private members and all of them support the three-way comparison operator.

In the next post I will have a look at if it is possible to use the spaceship operator when you only wish to compare some of the member variables.

,

Lämna ett svar

Din e-postadress kommer inte publiceras.