首页 > 解决方案 > 为什么 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;
}

标签: c++c++20spaceship-operator

解决方案


默认的比较运算符是选择加入,而不是选择退出。

如果它是选择退出的,那么它可以将无法编译的代码转换为具有某种未知含义的编译代码。标准委员会试图尽可能地保持向后兼容性。


推荐阅读