Namespaces
Variants

std:: to_underlying

From cppreference.net
Utilities library
헤더에 정의됨 <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)
타입이 열거형 타입인지 확인
(클래스 템플릿)
타입이 범위 지정 열거형 타입인지 확인
(클래스 템플릿)