C++ Type Traits | "타입 특성" 완벽 가이드
이 글의 핵심
C++ Type Traits에 대해 정리한 개발 블로그 글입니다. #include <type_traits> using namespace std;
기본 타입 체크
#include <type_traits>
using namespace std;
int main() {
cout << is_integral<int>::value << endl; // 1
cout << is_floating_point<double>::value << endl; // 1
cout << is_pointer<int*>::value << endl; // 1
cout << is_array<int[]>::value << endl; // 1
cout << is_class<string>::value << endl; // 1
}
타입 변환
// const 제거
remove_const<const int>::type // int
// 참조 제거
remove_reference<int&>::type // int
remove_reference<int&&>::type // int
// 포인터 추가/제거
add_pointer<int>::type // int*
remove_pointer<int*>::type // int
// CV 제거
remove_cv<const volatile int>::type // int
// decay
decay<int[10]>::type // int*
decay<int()>::type // int(*)()
타입 관계
// 같은 타입
is_same<int, int>::value // 1
is_same<int, long>::value // 0
// 변환 가능
is_convertible<int, double>::value // 1
is_convertible<int*, void*>::value // 1
// 상속 관계
is_base_of<Base, Derived>::value // 1
실전 예시
예시 1: 타입별 처리
template<typename T>
void process(T value) {
if constexpr (is_integral_v<T>) {
cout << "정수: " << value << endl;
} else if constexpr (is_floating_point_v<T>) {
cout << "실수: " << value << endl;
} else if constexpr (is_pointer_v<T>) {
cout << "포인터: " << value << endl;
} else {
cout << "기타 타입" << endl;
}
}
int main() {
process(10); // 정수
process(3.14); // 실수
process(&main); // 포인터
}
예시 2: SFINAE
// 정수 타입만
template<typename T>
enable_if_t<is_integral_v<T>, T>
twice(T value) {
return value * 2;
}
// 실수 타입만
template<typename T>
enable_if_t<is_floating_point_v<T>, T>
twice(T value) {
return value * 2.0;
}
int main() {
cout << twice(10) << endl; // 20
cout << twice(3.14) << endl; // 6.28
// twice("hello"); // 에러
}
예시 3: 타입 안전 직렬화
template<typename T>
string serialize(const T& value) {
if constexpr (is_arithmetic_v<T>) {
return to_string(value);
} else if constexpr (is_same_v<T, string>) {
return "\"" + value + "\"";
} else if constexpr (is_pointer_v<T>) {
return serialize(*value);
} else {
static_assert(always_false<T>, "지원하지 않는 타입");
}
}
template<typename T>
inline constexpr bool always_false = false;
int main() {
cout << serialize(42) << endl;
cout << serialize(3.14) << endl;
cout << serialize(string("Hello")) << endl;
}
예시 4: 컨테이너 체크
template<typename T, typename = void>
struct is_container : false_type {};
template<typename T>
struct is_container<T, void_t<
typename T::value_type,
decltype(declval<T>().begin()),
decltype(declval<T>().end())
>> : true_type {};
template<typename T>
inline constexpr bool is_container_v = is_container<T>::value;
int main() {
cout << is_container_v<vector<int>> << endl; // 1
cout << is_container_v<list<int>> << endl; // 1
cout << is_container_v<int> << endl; // 0
}
조건부 타입
// 조건부 타입 선택
conditional<true, int, double>::type // int
conditional<false, int, double>::type // double
// 사용 예
template<bool UseDouble>
using Number = conditional_t<UseDouble, double, int>;
Number<true> x = 3.14; // double
Number<false> y = 10; // int
타입 카테고리
// 기본 타입
is_void<void>::value
is_null_pointer<nullptr_t>::value
is_integral<int>::value
is_floating_point<double>::value
// 복합 타입
is_array<int[]>::value
is_pointer<int*>::value
is_reference<int&>::value
is_member_pointer<int Widget::*>::value
// 타입 속성
is_const<const int>::value
is_volatile<volatile int>::value
is_signed<int>::value
is_unsigned<unsigned int>::value
생성/소멸 특성
// 생성 가능
is_default_constructible<Widget>::value
is_copy_constructible<Widget>::value
is_move_constructible<Widget>::value
// trivial
is_trivially_copyable<int>::value
is_trivially_destructible<int>::value
// 소멸자
is_destructible<Widget>::value
has_virtual_destructor<Base>::value
자주 발생하는 문제
문제 1: _v vs ::value
// C++14 이전
if (is_integral<T>::value) {
}
// C++17 이후 (간결)
if (is_integral_v<T>) {
}
문제 2: enable_if 위치
// 반환 타입
template<typename T>
enable_if_t<is_integral_v<T>, T>
func(T value) {
return value * 2;
}
// 템플릿 매개변수
template<typename T, enable_if_t<is_integral_v<T>, int> = 0>
T func(T value) {
return value * 2;
}
문제 3: 복잡한 타입 체크
// ❌ 복잡
template<typename T>
enable_if_t<
is_integral<T>::value &&
is_signed<T>::value &&
sizeof(T) == 4,
T
>
func(T value) {
return value;
}
// ✅ Concepts 사용 (C++20)
template<typename T>
concept SignedInt32 = integral<T> && signed_integral<T> && sizeof(T) == 4;
template<SignedInt32 T>
T func(T value) {
return value;
}
커스텀 Traits
// 커스텀 trait
template<typename T>
struct is_string : false_type {};
template<>
struct is_string<string> : true_type {};
template<>
struct is_string<string_view> : true_type {};
template<typename T>
inline constexpr bool is_string_v = is_string<T>::value;
int main() {
cout << is_string_v<string> << endl; // 1
cout << is_string_v<string_view> << endl; // 1
cout << is_string_v<int> << endl; // 0
}
FAQ
Q1: type traits는 언제 사용하나요?
A:
- 템플릿 메타프로그래밍
- SFINAE
- 컴파일 타임 분기
- 타입 체크
Q2: 성능 오버헤드는?
A: 없습니다. 컴파일 타임에 모두 처리됩니다.
Q3: Concepts vs type traits?
A: C++20 이상이면 Concepts가 더 읽기 쉽습니다.
Q4: 커스텀 trait는?
A: true_type/false_type을 상속하여 구현.
Q5: type traits 디버깅은?
A: static_assert로 타입 체크.
Q6: Type Traits 학습 리소스는?
A:
- cppreference.com
- “C++ Templates: The Complete Guide”
- “Effective Modern C++“
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ SFINAE와 Concepts | “템플릿 제약” 가이드
- C++ enable_if | “조건부 컴파일” 가이드
- C++ SFINAE | “Substitution Failure Is Not An Error” 가이드
관련 글
- C++ SFINAE와 Concepts |
- C++ enable_if |
- C++ Expression Templates |
- C++ 메타프로그래밍의 진화: Template에서 Constexpr, 그리고 Reflection까지
- C++ 메타프로그래밍 고급 | SFINAE·Concepts·constexpr·타입 트레이트 가이드