c++ - 为什么 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;
}
解决方案
默认的比较运算符是选择加入,而不是选择退出。
如果它是选择退出的,那么它可以将无法编译的代码转换为具有某种未知含义的编译代码。标准委员会试图尽可能地保持向后兼容性。
推荐阅读
- r - 在 R 中:按组具有值 0、1 和 2 的子集观测值
- javascript - d3 v6 汇总中的动态键数
- react-native - 在 React Native 项目中更改 android SDK
- typescript - 如何用正确的类型替换函数参数?
- x11 - SDL2,X11,无桌面环境:没有焦点的应用程序,没有输入事件
- laravel - Laravel Eloquent Query 使用 Where、With、Where 和 orWhere 条件
- python - 下载问题:从win32com导入adsi
- ios - Firebase Crashlytics 问题:某些崩溃无法从我的 iPad 正确报告
- google-workspace - 如何从 Google 目录 API 获取所有 Gsuite 帐户应用程序?
- wordpress - WordPress 后期格式在 Gutenberb 编辑器中不可见