0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】enum と整数型

Posted at
2024/09/24

基底の整数型

enum class に基底の整数型を指定しない場合、int になる。

enum class Alpha { A = 0 };                                     // int
enum class Bravo { B = 0xFFFFFFFFFFFFFFFF };                    // エラー!表現できない値
enum class Charlie : std::uint64_t { C = 0xFFFFFFFFFFFFFFFF };  // OK

enum に基底の整数型を指定しない場合、どの整数型になるかは実装定義になる。ただし、表現できる値であれば int より大きいサイズの型にはならない。

enum Delta { D = 0 };                  // int 以下の整数型
enum Echo { E = 0xFFFFFFFFFFFFFFFF };  // たぶん std::uint64_t

std::underlying_type

std::underlying_type を使うと enum の基底型を取得することができる。

using type = std::underlying_type_t<Alpha>;  // int

enum を基底型に変換する関数を自作すると以下のようになる。

template <typename E>
auto enum_cast(E e)
{
    static_assert(std::is_enum<E>::value, "error");
    return static_cast<std::underlying_type_t<E>>(e);
}

なお、上記のものと同じ関数 std::to_underlying が C++23 にて追加される。

初期化リストによる変換(C++17)

C++17 では {} で enum class を初期化できる(C++ 14 までは static_cast を使う必要がある)。キャストと異なり、精度が足りない場合はエラーを出してくれる。

enum class Foxtrot : std::int8_t {};
Foxtrot a{0};               // C++17:OK, C++14:エラー!enum class を数値で初期化できない
Foxtrot b = Foxtrot{0};     // 上と同じ
Foxtrot c = Foxtrot{1000};  // エラー! int8_t で表現できない
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?