为什么C++20中的空结构没有隐式飞船运算符?
动机:有时我使用 std::variant 来实现“花式”枚举,其中一些枚举状态可以携带状态。
现在,如果我想将<=>用于我的变体,它需要我的空结构已经定义 <=>。这对我来说似乎有点奇怪,因为如果类型具有 0 位状态,则该类型的所有实例都是相同的。
完整示例:
#include <compare>
#include <iostream>
#include <variant>
struct Off{
// without this the code does not compile
auto operator<=>(const Off& other) const = default;
};
struct Running{
int rpm=1000;
auto operator<=>(const Running& other) const = default;
};
using EngineState = std::variant<Off, Running>;
int main()
{
EngineState es1, es2;
es1<=>es2;
}
回答
默认的比较运算符是选择加入,而不是选择退出。
如果它选择退出,那么它可以将无法编译的代码转换为具有某种未知含义的编译代码。标准委员会尽量保持向后兼容性。