utility_to_underlying

utility_to_underlying (열거형을 기반 타입으로 변환하기)

std::to_underlying 함수는 열거형 값을 그 기반 타입(underlying type)의 정수 값으로 변환해요. 이 함수는 C++23부터 사용할 수 있으며, 열거형을 기반 타입 이외의 정수 타입으로 잘못 변환하는 실수를 방지하는 데 유용해요. 이 페이지에서는 함수의 선언, 매개변수, 반환값, 예제 등을 자세히 설명할게요.

출처: cppreference

본문

Defined in header <utility>
template < class Enum > constexpr std :: underlying_type_t < Enum > to_underlying ( Enum e ) noexcept ; (since C++23)

열거형을 기반 타입으로 변환해요. return static_cast < std :: underlying_type_t < Enum >> ( e ) ; 와 동일해요.

매개변수

e - 변환할 열거형 값

반환값

Enum의 기반 타입의 정수 값으로, e에서 변환된 값이에요.

참고

std::to_underlying은 열거형을 기반 타입이 아닌 다른 정수 타입으로 변환하는 것을 피하기 위해 사용할 수 있어요.

Feature-test macro Value Std Feature
__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

같이 보기

underlying_type (C++11) 주어진 열거형 타입에 대한 기반 정수 타입을 얻어요 (클래스 템플릿)
is_enum (C++11) 타입이 열거형 타입인지 확인해요 (클래스 템플릿)
is_scoped_enum (C++23) 타입이 스코프 있는 열거형 타입인지 확인해요 (클래스 템플릿)

더 알아보기 (Learn more)

cppreference