Template Specialization in C++
Specialization customizes a template for specific types: the primary template handles the general case, while template <> struct Trait<MyType> { ... }; overrides behavior for MyType alone. The compiler always prefers the most specialized match — full specialization for exact types, partial specialization (classes only) for patterns like pointers (T*) or pairs.
Type traits (std::is_integral<T>::value) are the canonical application: a primary false answer with true specializations per qualifying type. Function templates can't partially specialize — overload instead.
Primary plus overrides
The general template covers everything; each template <> ... full specialization replaces it for one exact type.
Partial for patterns
Class templates also allow template <typename T> struct X<T*> — specializing a whole family (all pointers) at once.
Most specialized wins
Given several matches, the compiler picks the narrowest — exact type over pattern over primary, deterministically.
Functions overload instead
Function templates have no partial specialization — write an overload (or delegate to a specialized class) for the same effect.
#include <iostream>#include <string> template <typename T>std::string kind() { return "generic"; } template <>std::string kind<int>() { return "integer"; } int main() { std::cout << kind<double>() << ", " << kind<int>() << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.