![](/img/trans.png)
[英]What is the <=> ("spaceship", three-way comparison) operator in C++?
[英]How to use three-way comparison (spaceship op) to implement operator== between different types?
簡單任務:我有這兩種類型
struct type_a{
int member;
};
struct type_b{
int member;
};
我想使用這個新的 C++20 宇宙飛船操作,每個人都說它很酷,能夠編寫type_a{} == type_b{}
。 我沒能做到。 即使我在它們之間寫了operator<=>
,我也只能調用type_a{} <=> type_b{}
,但絕不是簡單的比較。 這讓我與單個 class 混淆,三路比較也定義了所有其他比較。
替代配方? 如何使std::three_way_comparable_with<type_a, type_b>
為真?
問題的前提是錯誤的。 您不使用三路比較運算符( <=>
)來實現==
:您使用==
來實現==
:
bool operator==(type_a a, type_b b) {
return a.member == b.member;
}
混淆的來源是這個規則有一個例外:如果一個類型聲明了一個默認的<=>
那么它也聲明了一個默認的==
:
struct type_c {
int member;
auto operator<=>(type_c const&) const = default;
};
該聲明相當於寫了:
struct type_c {
int member;
bool operator==(type_c const&) const = default;
auto operator<=>(type_c const&) const = default;
};
但不是<=>
給你==
:它仍然是==
,只有==
給你==
。
我建議將一種類型轉換為另一種類型:
struct type_a{
int member;
friend auto operator<=>(const type_a&, const type_a&) = default;
};
struct type_b{
int member;
operator type_a() {
return {member};
}
};
這也是 operator<=> 之前的解決方案,但現在定義通用類型的比較更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.