std::to_underlying
Aus cppreference.com
<tbody>
</tbody>
| definiert in Header <utility>
|
||
template< class Enum > constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept; |
||
Konvertiert einen Aufzählungswert in seinen zugrundeliegenden Typ. Das ist äquivalent zu return static_cast<std::underlying_type_t<Enum>>(e);.
Parameter
| e | - | Aufzählungswert, der konvertiert werden soll |
Rückgabewert
Der Ganzzahlwert des zugrundeliegenden Typs Enum, der von e konvertiert wurde.
Anmerkunegn
std::to_underlying kann benutzt werden, um zu verhindern, daß ein Aufzählungswert zu einem anderen Ganzzahltyp als dem zugrundeliegenden Typ konvertiert wird.
Feature testing macro: __cpp_lib_to_underlying
Beispiele
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <utility>
int main()
{
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))>);
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
}
Output:
000000FF
0000FF00
00FF0000
FF000000
Referenzen
(C++11) |
erhält die zugrunde liegende ganzzahlige Typ für eine bestimmte Aufzählungstyp Original: obtains the underlying integer type for a given enumeration type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (Klassen-Template) |
(C++11) |
prüft, ob eine Art ist ein Aufzählungstyp Original: checks if a type is an enumeration type The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (Klassen-Template) |
(C++23) |
überprüft, ob der Typ ein in sich abgeschlossener Aufzählungswert ist (Klassen-Template) |