to_underlying — std::to_underlying
to_underlying — std::to_underlying
std::to_underlying은 열거형을 그 기반 타입(underlying type)으로 변환하는 함수예요. C++23에서 도입됐어요. <utility> 헤더에 있어요.
static_cast<std::underlying_type_t<Enum>>(e)와 동등해요.
출처: cppreference
본문
// <utility> 헤더, C++23
template< class Enum >
constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept;
사용 예
#include <utility>
enum class Color : int { Red, Green, Blue };
enum Old { A, B }; // 기반 타입은 구현 정의 (보통 int)
int r = std::to_underlying(Color::Red); // 0
int g = std::to_underlying(Color::Green); // 1
왜 쓰는가
옛 방식 static_cast<int>(enum_value)는 기반 타입이 int가 아닐 수 있어 실수로 이어질 수 있어요. to_underlying은 항상 정확한 기반 타입으로 변환해요.
enum class Mask : unsigned long { A = 1UL << 33 };
// 정확한 기반 타입 (unsigned long)으로
auto v = std::to_underlying(Mask::A);
static_assert(std::is_same_v<decltype(v), unsigned long>);
특징
- constexpr,
noexcept— 컴파일 타임 사용 가능. - 열거형이 실제로 열거형이 아니면 ill-formed.
- 열거 값을 정수 연산(시프트, 마스크 등)에 쓰기 전에 기반 타입으로 안전하게 변환.
// 비트 마스크 처리
unsigned flags = std::to_underlying(opt1) | std::to_underlying(opt2);
std::to_underlying은 열거형 값을 정확한 기반 정수 타입으로 얻어 정수 연산을 안전하게 하는 C++23 도구예요.