Rom*_*sky 8 c++ spaceship-operator
以下代码调用 operator <=> 两次,参数颠倒。但为什么?
GCC 10.2 和 clang 12 似乎都在使用 libstdc++-10,其 <tuple> 确实提供了运算符 <=>,因此它似乎不是缺少标准库支持的情况,我的代码必须不正确。如何解决?
#include <tuple>
#include <compare>
#include <iostream>
struct X {
int i;
auto operator <=>(X const& other) const {
std::cout << this << " <=> " << &other << std::endl;
return i <=> other.i;
}
};
int main() {
std::tuple{X{42}} <=> std::tuple{X{42}};
}
Run Code Online (Sandbox Code Playgroud)
简短回答:您需要定义operator==for X。
std::tuple通过综合三向比较来比较元素,该比较<=>仅在类型满足时才使用std::three_way_comparable_with<T,U>。最终,这需要std::three_way_comparable<X>,这需要一个说明性weakly-equality-comparable-with概念。正如您可能猜到的,这需要==有效。
解决方法是一行:
bool operator==(X const& other) const = default;
Run Code Online (Sandbox Code Playgroud)
现在,==当<=>似乎在这里自己完成这项工作时,为什么还需要呢?我只能推测,但这可能是因为概念比我们习惯的仅需要operator<示例更“完整”。如果一个类型与 具有可比性<=>,那么它实际上也应该支持相等性。
至于为什么<=>不==单独覆盖,除非默认,这是因为相等性可以短路的类(例如向量和字符串)以及包含此类类型的任何类都会出现性能缺陷。不会给出任何指示相等性会比较每个元素而不是短路,因此<=>不会处理相等性,除非它可以保证您将避免该陷阱(通过 defaulting <=>)。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |