Understanding Partial Specialization
Understand the details of partial specialization in this lesson.
We'll cover the following...
In the previous lesson, we explored a variant of template specialization (explicit or full specialization). In this lesson, we’ll take a closer look at partial specialization, which is the second form of template specialization.
Partial specialization
Partial specialization occurs when we specialize a primary template but only specify some of the template arguments. This means a partial specialization has both a template parameter list (which follows the template keyword) and a template argument list (which follows the template name). However, only classes can be partially specialized.
Let’s explore the following example to understand how this works:
template<typename T, int S>struct collection{void operator()(){ std::cout << "primary template\n"; }};template<typename T>struct collection<T, 10>{void operator()(){ std::cout << "partial specialization <T, 10>\n"; }};template<int S>struct collection<int, S>{void operator()(){ std::cout << "partial specialization <int, S>\n"; }};template<typename T, int S>struct collection<T*, S>{void operator()(){ std::cout << "partial specialization <T*, S>\n"; }};
We have a primary template called collection
that has two template arguments (a type template argument and a non-type template argument), and we have three partial specializations, as follows:
A specialization for the non-type template argument
S
with the value10
A specialization for the
int
typeA specialization for the pointer type
T*
... ...