enum concepts
개요
C++20 Concept와 열거형(Enum)을 통합하여 타입 안전성과 가독성을 동시에 확보하는 방법을 설명합니다.
C++ 버전별 주요 키워드 도입 시기
- C++11: enum class
- C++20: concept
내용 설명
C++20에서 도입된 concept
는 템플릿 타입 매개변수에 대한 제약 조건을 명시적으로 정의할 수 있습니다. 열거형 전용 EnumType
concept를 정의하면, 템플릿 함수가 오직 열거형 타입만을 허용하도록 컴파일 타임에 검증합니다.
#include <type_traits>
#include <concepts>
// 열거형 타입 전용 Concept
template<typename T>
concept EnumType = std::is_enum_v<T>;
// 열거형 값을 기본 정수형으로 변환하는 제네릭 함수
template<EnumType T>
constexpr auto to_underlying(T value) {
return static_cast<std::underlying_type_t<T>>(value);
}
예제 코드
#include <iostream>
#include <cstdint>
#include <concepts>
#include <type_traits>
// EnumType Concept 정의
template<typename T>
concept EnumType = std::is_enum_v<T>;
// to_underlying 함수
template<EnumType T>
constexpr auto to_underlying(T value) {
return static_cast<std::underlying_type_t<T>>(value);
}
int main() {
enum class Status { OK = 0, ERROR = 1 };
enum class Byte : uint8_t { ZERO = 0, MAX = 255 };
std::cout << to_underlying(Status::OK) << std::endl; // 출력: 0
std::cout << to_underlying(Byte::MAX) << std::endl; // 출력: 255
static_assert(to_underlying(Status::ERROR) == 1);
static_assert(to_underlying(Byte::ZERO) == 0);
return 0;
}
실행 결과
위 함수를 사용한 예제 실행 시, 열거형 값이 안전하게 정수로 변환되어 출력됩니다.
0
255
활용팁
- 다양한 Concepts와 조합하여 열거형 기반 타입 특화 로직을 쉽게 구현할 수 있습니다.
static_assert
를 활용해 컴파일 타임 검증을 추가하면, 런타임 안전성을 더욱 강화할 수 있습니다.- 기존 코드에서
static_cast
를 직접 사용하던 부분을to_underlying
으로 대체하면 가독성이 향상됩니다.
'개발 > C++ (98,03,11,14,17,20,23)' 카테고리의 다른 글
Modern C++ : enum vs enum class (98, 11) (1) | 2025.08.02 |
---|---|
Modern C++ 둘러보기 (3) | 2025.08.01 |