types_underlying_type
types_underlying_type (기반 타입)
std::underlying_type은 열거형(enum) 타입의 기반 타입(underlying type)을 알아내는 템플릿이에요. 이 페이지에서는 템플릿의 정의와 멤버 타입, 사용 예제를 확인할 수 있어요. C++11부터 사용할 수 있고, C++14부터는 underlying_type_t 헬퍼 타입도 제공돼요.
출처: cppreference
본문
정의
<type_traits> 헤더에 정의되어 있어요.
template < class T > struct underlying_type ; |
(since C++11) |
T가 완전한 열거형(enum) 타입이라면, T의 기반 타입을 가리키는 멤버 typedef인 type을 제공해요.
- C++20 이전에는 그 외의 경우 동작이 정의되지 않았어요.
- C++20부터는
T가 열거형이 아니면 멤버type이 없고,T가 불완전한 열거형이면 프로그램이 ill-formed예요.
std::underlying_type에 특수화를 추가하면 동작이 정의되지 않아요.
멤버 타입
| Member type | Description |
|---|---|
type |
T의 기반 타입 |
헬퍼 타입
template < class T > using underlying_type_t = typename underlying_type < T >:: type ; |
(since C++14) |
Notes
각 열거형 타입은 기반 타입을 가지며, 이는 다음과 같이 결정돼요.
- 명시적으로 지정할 수 있어요 (scoped 및 unscoped 열거형 모두).
- 생략하면, scoped 열거형은
int, unscoped 열거형은 열거형의 모든 값을 표현할 수 있는 구현 정의 정수 타입이 돼요.
Example
#include <iostream>
#include <type_traits>
enum e1 {};
enum class e2 {};
enum class e3 : unsigned {};
enum class e4 : int {};
int main()
{
constexpr bool e1_t = std::is_same_v<std::underlying_type_t<e1>, int>;
constexpr bool e2_t = std::is_same_v<std::underlying_type_t<e2>, int>;
constexpr bool e3_t = std::is_same_v<std::underlying_type_t<e3>, int>;
constexpr bool e4_t = std::is_same_v<std::underlying_type_t<e4>, int>;
std::cout
<< "underlying type for ‘e1’ is " << (e1_t ? "int" : "non-int") << '\n'
<< "underlying type for ‘e2’ is " << (e2_t ? "int" : "non-int") << '\n'
<< "underlying type for ‘e3’ is " << (e3_t ? "int" : "non-int") << '\n'
<< "underlying type for ‘e4’ is " << (e4_t ? "int" : "non-int") << '\n';
}
Possible output:
underlying type for ‘e1’ is non-int
underlying type for ‘e2’ is int
underlying type for ‘e3’ is non-int
underlying type for ‘e4’ is int
결함 보고서
다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 2396 | C++11 | incomplete enumeration types were allowed | complete enumeration type required |
같이 보기
decltype specifier (C++11) |
표현식이나 개체의 타입을 얻어요 [edit] |
|---|---|
is_enum (C++11) |
타입이 열거형인지 확인해요 (클래스 템플릿) [edit] |
is_enum_type (C++26) |
반영된 타입이 열거형인지 확인해요 (함수) [edit] |
is_scoped_enum (C++23) |
타입이 scoped 열거형인지 확인해요 (클래스 템플릿) [edit] |
is_scoped_enum_type (C++26) |
반영이 scoped 열거형을 나타내는지 확인해요 (함수) [edit] |
to_underlying (C++23) |
열거형을 기반 타입으로 변환해요 (함수 템플릿) [edit] |
underlying_type (C++26) |
반영된 열거형 타입의 기반 정수 타입을 얻어요 (함수) [edit] |