728x90
컴파일 타임에 type을 체크하는 type_traits
type_traits 란?
경량 임베디드에 사용 가능한 STL을 만드는 HSTL이라는 Toy project를 하는 중인데
제일 처음 type_traits를 만들어야 한다고 함
type_traits은
- 컴파일 타임에 type을 체크하는 용도
- 템플릿 메타 프로그래밍의 기본 요소
- 템플릿은 “모든 타입을 다 받을 수” 있지만, 특정 타입에서만 다르게 처리하고 싶을 때가 많음
- 즉, 컴파일 타임 조건문(static if) 을 만드는 기반
#ifndef HSTL_TYPE_TRAITS_H
#define HSTL_TYPE_TRAITS_H
namespace hstl {
// integral_constant
template <typename T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant<T, v>;
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; }
};
// true_type and false_type
using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;
// is_same
template <typename T, typename U>
struct is_same : false_type {};
template <typename T>
struct is_same<T, T> : true_type {};
template <typename T, typename U>
inline constexpr bool is_same_v = is_same<T, U>::value;
} // namespace hstl
#endif // HSTL_TYPE_TRAITS_H
그래서 어떻게 사용하나?
- 사용 방법(Interface)은 다음과 같음 is_same_v<T, U>
- is_same_v<int, int> 는 true, is_same_v<int, unsigned int> 는 false를 반환
- 내부 로직을 살펴보면 integral_constant 구조체를 통해 true, false 값을 저장하고 반환
- 보통 static_assert 같이 compile 시점에 Error를 발생시키는 함수와 함께 사용
728x90
'TIL > 2025' 카테고리의 다른 글
| Hash와 Digital Signature (0) | 2025.12.09 |
|---|---|
| Confluence 문서 상태 관리 feat. Comala (0) | 2025.11.07 |
| [cpp] Request and Suppress (=default, =delete) (1) | 2025.09.08 |
| [cpp] Lambda Functions (0) | 2025.08.25 |
| for 조건문 내 후위 연산자의 위험성 (1) | 2025.08.15 |