std::to_underlying
來自 cppreference.com
在標頭檔案 <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
可以用於避免將列舉轉換為非其底層型別的整數型別。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__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) |
獲取給定列舉型別的底層整數型別 (類模板) |
(C++11) |
檢查一個型別是否是列舉型別 (類模板) |
(C++23) |
檢查一個型別是否是有作用域的列舉型別 (類模板) |