template_specialization — 명시적 템플릿 특수화

template_specialization — 명시적 템플릿 특수화 (Explicit template specialization)

**명시적(완전) 템플릿 특수화(explicit/full template specialization)**는 주어진 템플릿 인자 집합에 대해 템플릿 코드를 커스터마이즈할 수 있게 해주는 기능이에요.

주 템플릿의 동작을 특정 타입에 대해 완전히 새로 정의하고 싶을 때 사용해요.

출처: cppreference

본문

문법 (Syntax)

template <> declaration

다음 중 어떤 것도 완전히 특수화할 수 있어요.

  1. 함수 템플릿
  2. 클래스 템플릿
  3. 변수 템플릿
  4. 클래스 템플릿의 멤버 함수
  5. 클래스 템플릿의 정적 데이터 멤버
  6. 클래스 템플릿의 멤버 클래스
  7. 클래스 템플릿의 멤버 열거형
  8. 클래스 또는 클래스 템플릿의 멤버 클래스 템플릿
  9. 클래스 또는 클래스 템플릿의 멤버 함수 템플릿
  10. 클래스 또는 클래스 템플릿의 멤버 변수 템플릿
// 주 템플릿
template<typename T>
struct IsInt {
    static constexpr bool value = false;
};

// int에 대한 완전 특수화
template<>
struct IsInt<int> {
    static constexpr bool value = true;
};

IsInt<int>::value    // true
IsInt<double>::value // false

함수 템플릿의 완전 특수화:

template<typename T>
std::string describe(T) { return "generic"; }

template<>
std::string describe<int>(int) { return "an integer"; }

describe(3.14);  // "generic"
describe(42);    // "an integer"

주의할 점:

  • 완전 특수화는 template<>로 모든 템플릿 매개변수를 구체화해요. 부분 특수화(일부만 특정)와 다르게, 함수 템플릿도 완전 특수화는 가능해요.
  • 특수화는 주 템플릿이 선언된 어떤 네임스페이스에서든 선언할 수 있어요. 함수 템플릿 특수화는 보통 정의된 파일에 두는 것이 안전해요 (헤더에 두면 ODR 문제 가능).
// class 템플릿 특수화의 또 다른 예
template<> struct MyContainer<char> { /* char 전용 */ };

완전 특수화는 std::hash 같은 표준 템플릿을 사용자 타입에 맞게 확장하거나, 특정 타입에 최적화된 구현을 제공할 때 자주 쓰여요.

더 알아보기 (Learn more)

cppreference