Course Content
C++ Templates
C++ Templates
Partial Template Specialization
Template specialization for a single-parameter template is straightforward, but it becomes more complex with multiple parameters. This is where partial template specialization comes in. It allows you to create a specialized version of a template for specific subsets of types or values.
main
// What if `T1` and `T2` are the same type? // Or what if you want to define special behavior when `T1` is a `std::string`? template<typename T1, typename T2> void TemplateExample(T1 first, T2 second) { std::cout << "Generic template!" << std::endl; }
Syntax of Partial Template Specialization
You can think of partial template specialization as a form of template overloading. Here are the rules to follow:
In partial specialization, you define a new version of a template function with some of its parameters fixed to specific types while leaving others as generic. The compiler uses this specialized version whenever it encounters matching types during template instantiation.
main
#include <iostream> // Primary template template<typename T1, typename T2> bool IsSameType(T1 first, T2 second) { return false; } // Partial specialization for when both types are the same template<typename T> bool IsSameType(T first, T second) { return true; } int main() { std::cout << IsSameType(10, 'a') << std::endl; std::cout << IsSameType("Hello", "World") << std::endl; }
That is one way to use template specialization, but there is another, more common scenario.
main
#include <iostream> // Primary template template <typename T1, typename T2> // General case void Template(T1 a, T2 b) { std::cout << "General" << std::endl; } // Partial specialization for when `T1` is `bool` template <typename T2> // Special case when the first type is `bool` void Template(bool a, T2 b) { std::cout << "Special" << std::endl; } int main() { Template(false, 25); Template(100, 300); }
Thanks for your feedback!