[英]How to use three-way comparison (spaceship op) to implement operator== between different types?
Simple Task: I have these two types简单任务:我有这两种类型
struct type_a{
int member;
};
struct type_b{
int member;
};
I want to use this new C++20 spaceship op that everyone says is so cool to be able to write type_a{} == type_b{}
.我想使用这个新的 C++20 宇宙飞船操作,每个人都说它很酷,能够编写
type_a{} == type_b{}
。 I didn't manage to do that.我没能做到。 Even if I write
operator<=>
between them, I only ever can call type_a{} <=> type_b{}
, but never a simple comparison.即使我在它们之间写了
operator<=>
,我也只能调用type_a{} <=> type_b{}
,但绝不是简单的比较。 That confuses me as with a single class, the three-way comparison also defines all the others.这让我与单个 class 混淆,三路比较也定义了所有其他比较。
Alternative formulation?替代配方? How to make it so that
std::three_way_comparable_with<type_a, type_b>
is true?如何使
std::three_way_comparable_with<type_a, type_b>
为真?
The premise of the question is wrong.问题的前提是错误的。 You don't use the three-way comparison operator (
<=>
) to implement ==
: you use ==
to implement ==
:您不使用三路比较运算符(
<=>
)来实现==
:您使用==
来实现==
:
bool operator==(type_a a, type_b b) {
return a.member == b.member;
}
The source of confusion is that there is one exception to this rule: if a type declares a defaulted <=>
then it also declares a defaulted ==
:混淆的来源是这个规则有一个例外:如果一个类型声明了一个默认的
<=>
那么它也声明了一个默认的==
:
struct type_c {
int member;
auto operator<=>(type_c const&) const = default;
};
That declaration is equivalent to having written:该声明相当于写了:
struct type_c {
int member;
bool operator==(type_c const&) const = default;
auto operator<=>(type_c const&) const = default;
};
But it's not the <=>
that gives you ==
: it's still the ==
, and only ==
, that gives you ==
.但不是
<=>
给你==
:它仍然是==
,只有==
给你==
。
I recommend making one type convertible to the other:我建议将一种类型转换为另一种类型:
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};
}
};
This was the solution before operator<=> too, but now it's simpler to define the comparisons for the common type.这也是 operator<=> 之前的解决方案,但现在定义通用类型的比较更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.