Template Specialization (C++)
Kajanan introduced this to me, and I learned about it through Eigen.
Template specialization allows you to provide a specific implementation of a template for a particular data type or set of data types.
When is this ever useful?
This is useful when a general template definition does not suffice, or when a specific type requires optimization or a different behavior.
I learned this through ChatGPT.
Resources
- https://en.cppreference.com/w/cpp/language/template_specialization
- https://www.geeksforgeeks.org/template-specialization-c/
Class Template Specialization
First, you define a primary template that will work for most types:
Then, you provide an explicit specialization for a certain type
Do I need to reimplement the entire class if I do template specialization?
Unfortunately, yes… Yes, for class template specialization in C++, you need to redefine the entire class for the specialized type. Umm, unless you do CRTP? StackOverflow thread
Function Template Specialization
Similarly, function templates can also be specialized.
The primary template:
Specialized template
Then, this is what happens