Loading lessons...
Template Specialization
Template Specialization
Sometimes the general template is not the best behavior for one specific type. Template specialization lets you write a different implementation just for that type, while the generic one stays for everything else.
The generic version first
template <typename T>
void describe(T value) {
cout << "value: " << value << "\n";
}
describe(42) and describe(1.5) will use this generic version.
A custom version for const char*
template <>
void describe(const char* msg) {
cout << "text: " << msg << "\n";
}
What changed is in the header:
- The empty
template<>list: no placeholder remains, the type is fully fixed. - The description
const char*marks the one type this version handles.
describe("hi") matches const char*, so the specialized version wins over the generic one.
Why specialize const char*
The generic printer would print whatever the generic branch does with a pointer. The specialized version handles text in the way we want. Custom behavior per type is exactly what specialization is for.
TL;DR
- A specialization overrides the generic template for one specific type.
- Write
template <>with a concrete type signature. const char*can need different handling than numeric types.- All other types still use the generic template.