繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM