【发布时间】:2021-05-16 10:13:13
【问题描述】:
以下代码调用运算符 两次,参数颠倒。但为什么呢?
GCC 10.2 和 clang 12 似乎都在使用 libstdc++-10,其
#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}};
}
【问题讨论】:
-
@IgorR。您是在暗示 X 不是 three_way_comparable 吗?
-
这不是意料之中的吗?它必须提供三个之一?
a < b、b < a或相等?比如return a < b ? -1 : b < a ? 1 : 0,在 2/3 的情况下也需要进行 2 次比较。 -
@TedLyngmo 但是 X::operator 可以在一次调用中回答问题,这就是它存在的全部原因。
-
@RomanOdaisky 它为您生成运算符。我不明白它怎么能让一些比较消失。
-
嗯,是的,你们可能都是对的。 :-) 我会回去做饭。