![](/img/trans.png)
[英]What is the <=> ("spaceship", three-way comparison) operator in C++?
[英]Why default three-way operator (spaceship <=>) generates equality operator (==) and user define three-way operator not?
考虑这段代码:
#include <iostream>
#include <compare>
class A {
public:
int i = {};
std::strong_ordering operator<=> (A const& r) const
{
return i <=> r.i;
}
};
void TestA()
{
A a;
A b;
std::cout<< (a<b);
std::cout<< (a>b);
std::cout<< (a<=b);
std::cout<< (a>=b);
//std::cout<< (a==b); //ERROR
std::cout << 'E';
//std::cout<< (a!=b); //ERROR
std::cout << 'E';
std::cout<< std::is_eq(a<=>b);
std::cout<< std::is_neq(a<=>b) << std::endl;
}
class B {
public:
int i = {};
std::strong_ordering operator<=> (B const& r) const = default;
};
void TestB()
{
B a;
B b;
std::cout<< (a<b);
std::cout<< (a>b);
std::cout<< (a<=b);
std::cout<< (a>=b);
std::cout<< (a==b);
std::cout<< (a!=b);
std::cout<< std::is_eq(a<=>b);
std::cout<< std::is_neq(a<=>b) << std::endl;
}
class C {
public:
bool b = {};
int v1 = {};
int v2 = {};
std::strong_ordering operator<=> (C const& r) const
{
return (b?v1:v2) <=> (r.b?r.v1:r.v2);
}
bool operator== (C const& r) const
{
return std::is_eq(*this<=>r);
}
};
void TestC()
{
C a;
C b;
std::cout<< (a<b);
std::cout<< (a>b);
std::cout<< (a<=b);
std::cout<< (a>=b);
std::cout<< (a==b);
std::cout<< (a!=b);
std::cout<< std::is_eq(a<=>b);
std::cout<< std::is_neq(a<=>b) << std::endl;
}
int main()
{
TestA();
TestB();
TestC();
return 0;
}
https://wandbox.org/permlink/SLmLZOc18RaJV7Mu
删除评论以获取错误。
首先我想问一下为什么默认的三路运算符的行为与用户定义的运算符不同?
其次,这个问题的解决方案对于 class C
是否正确,还是应该以不同的方式处理?
这只是一个简单的例子,我对数十个字段和联合有更复杂的情况(如果你不明白我的意思,请查看一些英特尔 API;))。
编辑:
这个问题Equality operator does not get defined for a custom spaceship operator implementation in C++20重点是为什么用户定义的 3 路运算符没有默认相等运算符,我想知道为什么默认值和用户存在差异定义行为?
编辑2:
我在示例中稍微修改了 class C
以描绘更多现实生活中的问题(当默认运算符不是有效的解决方案时)。 我还想澄清一下,我想知道这些差异背后的原因(用户定义和默认运算符之间),以便能够评估我的现实生活中的解决方案是否正确(类似于C
),因为我确实更看重代码可维护性而不是性能对于我现在正在工作的部分代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.