-1

動機: 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;
}
4

2 に答える 2

5

デフォルトの比較演算子はオプトインであり、オプトアウトではありません。

オプトアウトの場合、コンパイルされないコードが、何らかの意味でコンパイルされるコードに変わる可能性があります。標準化委員会は、後方互換性を可能な限り維持しようとしています。

于 2021-02-26T15:27:59.077 に答える