【发布时间】:2021-09-14 03:53:50
【问题描述】:
#include <compare>
struct A
{
int n;
auto operator<=>(A const& other) const
{
if (n < other.n)
{
return std::strong_ordering::less;
}
else if (n > other.n)
{
return std::strong_ordering::greater;
}
else
{
return std::strong_ordering::equal;
}
}
// compile error if the following code is commented out.
// bool operator==(A const& other) const
// { return n == other.n; }
};
int main()
{
A{} == A{};
}
为什么我必须提供 operator == 何时 operator <=> 足够了?
【问题讨论】:
-
为什么
<=>不包括==?我的意思是,如果提供了==,请使用它;如果没有,请改用<=>?为什么C++标准不是这样设计的? -
你知道......我链接的第二个副本也是你问的......
-
@HansOlsson:你无法改变人们代码的含义和行为。此外,您不能基于返回类型重载,因此无法请求 特定类型的排序。您只能使用该类型提供的内容,并且已经依赖于标准库类型的现有排序运算符。你的建议是行不通的。
-
这个问题是另一个问题的副本:stackoverflow.com/q/58780829/1896169,但我不想将其作为副本关闭,因为这里的答案提供了不同的信息/不同的观点来帮助理解相同的信息...
标签: c++ language-lawyer c++20 language-design spaceship-operator