三路比较运算符 <=> 也被称为宇宙飞船运算符(spaceship operator)。
三路比较运算符表达式的形式为:
左操作数<=>右操作数
为什么引入
如果项目中使用struct的值用作std::map的key,因此就需要自己实现比较运算符。如果实现得不对(可能会出现自相矛盾,a < b 且 b < a),程序可能会崩溃。
struct Name {
string first_name;
string mid_name;
string last_name;
};
//C++11前
bool operator<(const Name& other) const {
return first_name<other.first_name
|| first_name == other.first_name && mid_name < other.mid_name
|| first_name == other.first_name && mid_name == other.mid_name && last_name < other.last_name;
}
//C++11后
bool operator<(const Name& other) const {
return std::tie(first_name, mid_name, last_name) <
std::tie(other.first_name, other.mid_name, other.last_name);
}
//C++20
struct Name {
string first_name;
string mid_name;
string last_name;
//编译器默认实现,注入语义,强序
std::strong_ordering operator<=>(const Name&) const = default;
};
在C++17, 需要 18 比较函数:
class CIString {
string s;
public:
friend bool operator==(const CIString& a, const CIString& b) {
return a.s.size() == b.s.size() &&
ci_compare(a.s.c_str(), b.s.c_str()) == 0;
}
friend bool operator< (const CIString& a, const CIString& b) {
return ci_compare(a.s.c_str(), b.s.c_str()) < 0;
}
friend bool operator!=(const CIString& a, const CIString& b) {
return !(a == b);
}
friend bool operator> (const CIString& a, const CIString& b) {
return b < a;
}
friend bool operator>=(const CI