std::to_underlying
From 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 | - | 変換する列挙値 |
[編集] 戻り値
e から変換された、Enum の基底型の整数値。
[編集] 備考
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) |
型がスコープ付き列挙型であるかをチェックする (クラステンプレート) |