Partial Template Specialization in C++
Last Updated :
04 Dec, 2023
In C++, template specialization enables us to define specialized versions of templates for some specific argument patterns. It is of two types:
- Full Template Specialization
- Partial Template Specialization
In this article, we will discuss the partial template specialization in C++ and how it is different from the full template specialization
Partial Template Specialization in C++
In C++, partial template specialization allows us to define a specialized version of the template for some of the template arguments in contrast to full template specialization which requires all the arguments to be defined.
Partial template specialization can be defined for all template types, i.e., class template, function template, and variable template.
Syntax of Partial Template Specialization
The syntax for partial template specialization depends on our requirement, template type, and number of templates. In General,
1. For Class Templates
Consider the primary class template:
template <class T, class X>
class Geek {
// General implementation for the primary template
};
If we want a specialization of the class Geek only for argument X as an integer, we use template specialization like this:
template < class T>
class Geek<T, int> {
// Specialized implementation for the primary template
}
2. For Function Templates
Let the primary function template be:
template <typename A, typename B>
void function(A var, B str) {
// General implementation for the primary template
}
To specialize the above function template for A as a pointer, we can use the following syntax:
template <typename A, typename B>
void function (A* var, B str) {
// Specialized implementation for the primary template
}
Examples of Partial Template Specialization
Example 1: C++ Program to illustrate Partial Specialization of Class Template
C++
#include <iostream>
using namespace std;
template < typename T, typename X>
class Geek {
public :
void Print() { cout << "Primary Template" << endl; }
};
template < typename T> class
Geek<T, int > {
public :
void Print()
{
cout << "Partial Specialization for int" << endl;
}
};
int main()
{
Geek< bool , double > obj1;
Geek< bool , int > obj2;
obj1.Print();
obj2.Print();
return 0;
}
|
Output
Primary Template
Partial Specialization for int
Example 2: C++ Program to illustrate Partial Specialization of Function Template
C++
#include <iostream>
using namespace std;
template < typename A, typename B>
void foo(A var, B str)
{
cout << "Primary Template" << endl;
}
template < typename A, typename B>
void foo(A* var, B str)
{
cout << "Partial Specialization Template" << endl;
}
int main()
{
int var = 10;
int * ptr = &var;
foo(var, "Geek" );
foo(ptr, 24);
return 0;
}
|
Output
Primary Template
Partial Specialization Template
Share your thoughts in the comments
Please Login to comment...