C++20 three way comparison operator — ensure backward compatibility: Part 8
In part one till seven of the tutorial series, we looked at how to use the C++20’s three way comparison operator. In this part of the tutorial series, we’ll look at the compatibility issues when using objects that were constructed before C++20 with the three way comparison operator and how to resolve them
1. Introduction
Consider the code below:
struct Cpp17{
int num_;
bool operator==(const Cpp17& rhs)const{
return (num_ == rhs.num_)
}
bool operator <(const Cpp17& rhs)const{
return (num_ < rhs.num_);
} bool operator >(const Cpp17& rhs)const{
return (num_ > rhs.num_);
}
} struct Cpp20{
Cpp17 obj_;
auto operator <=>(const Cpp20& rhs) const = default;
};
Writing such code may be fine until one tries to use and compare them:
int main(){
Cpp20 a, b;
auto result = a <=> b;
}
This results in a compiler error. On my machine with gcc 10.2, I get the following compiler error (only the relevant error information is shown):
...
...
no match for 'operator<=>' (operand types are 'Cpp17' and 'Cpp17')| Cpp17 obj_;
|…