0Pricing
C++ Academy · Lesson

Partial Specialization

Specialize template patterns.

What Is Partial Specialization?

Partial specialization customizes a template for a family of types that share a pattern, rather than one exact type.

  • Only class templates support it.
  • You still leave some parameters generic.
#include <iostream>

template <typename T>
struct Traits { static const char* kind() { return "value"; } };

template <typename T>
struct Traits<T*> { static const char* kind() { return "pointer"; } };

int main() {
    std::cout << Traits<int>::kind() << '\n';
    std::cout << Traits<int*>::kind() << '\n';
    return 0;
}

Matching Pointers

The pattern T* matches any pointer type, letting you handle all pointers with one specialization.

#include <iostream>

template <typename T>
struct Deref { static T get(T v) { return v; } };

template <typename T>
struct Deref<T*> { static T get(T* p) { return *p; } };

int main() {
    int x = 42;
    std::cout << Deref<int>::get(7) << '\n';
    std::cout << Deref<int*>::get(&x) << '\n';
    return 0;
}

All lessons in this course

  1. Full Specialization
  2. Partial Specialization
  3. SFINAE
  4. enable_if Patterns
← Back to C++ Academy