std::to_underlying
来自 cppreference.cn
定义于头文件 <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
可用于避免将枚举转换为其底层类型以外的整数类型。
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_to_underlying |
202102L |
(C++23) | std::to_underlying
|
[编辑] 示例
运行此代码
#include <cstdint> #include <iomanip> #include <iostream> #include <type_traits> #include <utility> enum class E1 : char { e }; static_assert(std::is_same_v<char, decltype(std::to_underlying(E1::e))>); enum struct E2 : long { e }; static_assert(std::is_same_v<long, decltype(std::to_underlying(E2::e))>); enum E3 : unsigned { e }; static_assert(std::is_same_v<unsigned, decltype(std::to_underlying(e))>); int main() { 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) << std::to_underlying(ColorMask::red) << '\n' << std::setw(8) << std::to_underlying(ColorMask::green) << '\n' << std::setw(8) << std::to_underlying(ColorMask::blue) << '\n' << std::setw(8) << std::to_underlying(ColorMask::alpha) << '\n'; // std::underlying_type_t<ColorMask> x = ColorMask::alpha; // Error: no known conversion [[maybe_unused]] std::underlying_type_t<ColorMask> y = std::to_underlying(ColorMask::alpha); // OK }
输出
000000FF 0000FF00 00FF0000 FF000000
[编辑] 参见
(C++11) |
underlying_type 获取给定枚举类型的底层整数类型(类模板) |
(C++11) |
is_enum 检查类型是否为枚举类型(类模板) |
(C++23) |
is_scoped_enum 检查类型是否为作用域枚举类型(类模板) |