如何使用三向比较(spaceship op)实现不同类型之间的operator==?

Bas*_*sti 3 c++ spaceship-operator c++20

简单任务:我有这两种类型

struct type_a{
   int member;
};

struct type_b{
   int member;
};
Run Code Online (Sandbox Code Playgroud)

我想使用这个新的 C++20 太空飞船操作,每个人都说它太酷了,能够编写type_a{} == type_b{}. 我没能做到这一点。即使我operator<=>在它们之间写,我也只能调用type_a{} <=> type_b{},而不能进行简单的比较。这让我感到困惑,因为只有一个类,三向比较也定义了所有其他类。

替代配方?怎样才能做到这一点std::three_way_comparable_with<type_a, type_b>呢?

Bar*_*rry 5

问题的前提是错误的。您不使用三向比较运算符 ( <=>) 来实现==:您使用三向==比较运算符来实现==

bool operator==(type_a a, type_b b) {
    return a.member == b.member;
}
Run Code Online (Sandbox Code Playgroud)

混乱的根源在于这一规则有一个例外:如果一个类型声明了一个defaulted <=>,那么它声明了一个defaulted ==

struct type_c {
    int member;
    auto operator<=>(type_c const&) const = default;
};
Run Code Online (Sandbox Code Playgroud)

该声明相当于写了:

struct type_c {
    int member;
    bool operator==(type_c const&) const = default;
    auto operator<=>(type_c const&) const = default;
};
Run Code Online (Sandbox Code Playgroud)

但这并不是<=>给你的==:它仍然是==,也是唯一==给你的==