簡單任務:我有這兩種型別
struct type_a{
int member;
};
struct type_b{
int member;
};
我想使用這個新的 C 20 宇宙飛船操作,每個人都說它很酷,可以寫type_a{} == type_b{}。我沒能做到。即使我operator<=>在它們之間寫,我也只能呼叫type_a{} <=> type_b{},但從來沒有簡單的比較。這讓我很困惑,因為只有一個類,三向比較也定義了所有其他類。
替代配方?如何使它成為std::three_way_comparable_with<type_a, type_b>真的?
uj5u.com熱心網友回復:
問題的前提是錯誤的。您不使用三路比較運算子 ( <=>) 來實作==:您使用==來實作==:
bool operator==(type_a a, type_b b) {
return a.member == b.member;
}
混淆的根源在于該規則有一個例外:如果一個型別宣告了defaulted <=>,那么它也宣告了一個defaulted ==:
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;
};
但它不是<=>給你==的:它仍然是==,也是唯一==的,給你==。
uj5u.com熱心網友回復:
我建議將一種型別轉換為另一種型別:
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<=> 之前的解決方案,但現在定義通用型別的比較更簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410791.html
標籤:
下一篇:在C 中決議文本檔案行
