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
- Full Specialization
- Partial Specialization
- SFINAE
- enable_if Patterns