Specialization
Let's learn about template specialization in this lesson.
Specialization #
Template specialization addresses the need to have different code for different template argument types. Templates define the behavior of families of classes and functions.
- Often it is necessary that special types, non-types, or templates as arguments are treated specially.
- We can fully specialize templates; class templates can even be partially specialized.
- The methods and attributes of specialization don’t have to be identical.
- General or Primary templates can coexist with partially or fully specialized templates.
The compiler prefers fully specialized to partially specialized templates and partially specialized templates to primary templates.
Primary Template #
The primary template has to be declared before the partially or fully specialized templates.
If the primary template is not needed, just a declaration will suffice.
template <typename T, int Line, int Column> class Matrix;
template <typename T>
class Matrix<T, 3, 3>{};
template <>class Matrix<int, 3, 3>{};
Partial specialization #
The partial specialization of a template is only supported for class templates. They contain template arguments and template parameters.
Get hands-on with 1400+ tech skills courses.