# std::to_underlying

< cpp‎ | utility

定义于头文件 `<utility>` |  |
template< class Enum > constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept; |  | (C++23 起)

转换枚举到其底层类型。等价于 return static_cast<std::underlying_type_t<Enum>>(e); 。

### 参数

e | - | 要转换的枚举值

### 返回值

`Enum` 的底层类型的整数值，从 `e` 转换得到。

### 注解

`std::to_underlying` 能用于避免将枚举类型转换成其底层类型以外的整数类型。

### 示例

    #include <cstdint>
    #include <iomanip>
    #include <iostream>
    #include <type_traits>
    #include <utility>

    namespace cxx {
    #if defined(__cpp_lib_to_underlying)
        using std::to_underlying;
    #else
        template <class Enum>
        constexpr std::underlying_type_t<Enum>
        to_underlying(Enum e) noexcept {
            return static_cast<std::underlying_type_t<Enum>>(e);
        }
    #endif
    }

    int main()
    {
        enum class E1 : char { e };
        static_assert(std::is_same_v<char, decltype(cxx::to_underlying(E1::e))>);
        enum struct E2 : long { e };
        static_assert(std::is_same_v<long, decltype(cxx::to_underlying(E2::e))>);
        enum E3 : unsigned { e };
        static_assert(std::is_same_v<unsigned, decltype(cxx::to_underlying(e))>);

        enum class ColorMask : std::uint32_t {
            red = 0xFF, green = (red << 8), blue = (green << 8), alpha = (blue << 8)
        };
        std::cout << std::hex << std::uppercase << std::setfill('0')
            << std::setw(8) << cxx::to_underlying(ColorMask::red) << '\n'
            << std::setw(8) << cxx::to_underlying(ColorMask::green) << '\n'
            << std::setw(8) << cxx::to_underlying(ColorMask::blue) << '\n'
            << std::setw(8) << cxx::to_underlying(ColorMask::alpha) << '\n';

    //  std::underlying_type_t<ColorMask> x = ColorMask::alpha; // 错误：无已知转换
        [[maybe_unused]]
        std::underlying_type_t<ColorMask> y = cxx::to_underlying(ColorMask::alpha); // OK
    }

输出：

    000000FF
    0000FF00
    00FF0000
    FF000000

### 参阅

underlying_type (C++11) | 获取给定枚举类型的底层整数类型 (类模板)