std:: to_underlying
|
Definiert im Header
<utility>
|
||
|
template
<
class
Enum
>
constexpr std:: underlying_type_t < Enum > to_underlying ( Enum e ) noexcept ; |
(seit C++23) | |
Wandelt eine Enumeration in ihren zugrundeliegenden Typ um. Entspricht return static_cast < std:: underlying_type_t < Enum >> ( e ) ; .
Inhaltsverzeichnis |
Parameter
| e | - | Enumerationswert zur Konvertierung |
Rückgabewert
Der ganzzahlige Wert des zugrundeliegenden Typs von
Enum
, konvertiert von
e
.
Hinweise
std::to_underlying
kann verwendet werden, um zu vermeiden, dass eine Aufzählung in einen anderen Ganzzahltyp als ihren zugrunde liegenden Typ konvertiert wird.
| Feature-Test Makro | Wert | Std | Feature |
|---|---|---|---|
__cpp_lib_to_underlying
|
202102L
|
(C++23) |
std::to_underlying
|
Beispiel
#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; // Fehler: keine bekannte Konvertierung [[maybe_unused]] std::underlying_type_t<ColorMask> y = std::to_underlying(ColorMask::alpha); // OK }
Ausgabe:
000000FF 0000FF00 00FF0000 FF000000
Siehe auch
|
(C++11)
|
ermittelt den zugrundeliegenden Ganzzahltyp für einen gegebenen Aufzählungstyp
(Klassentemplate) |
|
(C++11)
|
prüft, ob ein Typ ein Aufzählungstyp ist
(Klassentemplate) |
|
(C++23)
|
prüft, ob ein Typ ein scoped enumeration type ist
(Klassentemplate) |