Template Specialization in C++

12 Jun, 2022
Template in C++is a feature. We write code once and use it for any data type including user defined data types. For example, sort() can be written and used to sort any data type items. A class stack can be created that can be used as a stack of any data type. What if we want a different code for a particular data type? Consider a big project that needs a function sort() for arrays of many different data types. Let Quick Sort be used for all datatypes except char. In case of char, total possible values are 256 and counting sort may be a better option. Is it possible to use different code only when sort() is called for char data type? It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. 
Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.Templates are sometimes called parameterized classes or functions.
C++
// Eg: Let us recall the concept of function overloading #include<iostream>using namespace std; void show(int,int);void show(double,double);void show(char,char); main(){    show(2,5);    show(2.6,7.6);    return 0;} void show(int a,int b){    cout<<"a="<<a<<endl;    cout<<"b="<<b<<endl;} void show(double a,double b){    cout<<"a="<<a<<endl;    cout<<"b="<<b<<endl;}
a=2
b=5
a=2.6
b=7.6
But a careful observation of overloaded functions as in our program will show us the disadvantage of overloaded function. That is, each overloaded function definition does identical tasks. But the only change/difference with the overloaded function is that, they are handling arguments of different data types to do identical tasks. This is a disadvantage because, the data types of function arguments are different, we are writing separate code for function definition for performing the same task.This is one kind of disadvantage and this disadvantage is overcome by a new concept called “FUNCTION TEMPLATE”.  
CPP
// A generic sort functiontemplate <class T>void sort(T arr[], int size){    // code to implement Quick Sort} // Template Specialization: A function// specialized for char data typetemplate <>void sort<char>(char arr[], int size){    // code to implement counting sort}
Another example could be a class Set that represents a set of elements and supports operations like union, intersection, etc. When the type of elements is char, we may want to use a simple boolean array of size 256 to make a set. For other data types, we have to use some other complex technique.
Function templates allow the programmer to write a generic function which is independent of data type.Using function templates we can reduces the size of the code and makes the maintenance code easy. 
Syntax:
template <class T>
<return-type> <function-name> (  <parameters of type T> )
{
                 //function body
}
Where
template   ------    keyword
class T     ------    template type parameter enclosed within a pair of angle brackets(< >) called generic dt.
C++
// Example: #include<iostream>using namespace std; template<class T>void show(T a,T b){    cout<<"a="<<a<<endl;    cout<<"b="<<b<<endl;} main(){    show(2,5);    show(2.6,7.6);    return 0;}
a=2
b=5
a=2.6
b=7.6
C++
// Create a function template that prints the maximum of two values. #include<iostream>using namespace std; template<class T>void getMax(T a,T b){    T result;    result=(a>b)?a:b;    cout<<endl<<"Maximum:"<<result;} main(){    getMax(2,5);    getMax(2.6,7.6);    getMax('A','D');    return 0;}
Maximum:5
Maximum:7.6
Maximum:D
 
C++
// Example: #include<iostream>using namespace std; template<class T>T getMax(T a,T b){    T result;    result=(a>b)?a:b;    return result;} main(){  int a=getMax(2,5);  double d=getMax(2.6,7.6);  cout<<endl<<a;  cout<<endl<<d;    return 0;}
5
7.6
C++
// create a function template that prints the swap of two numbers. #include<iostream>using namespace std; template<class T>void swapp(T &a,T &b){    T temp;    temp=a;    a=b;    b=temp;} main(){  int a=10,b=20;  double x=20.3,y=55.3;    cout<<endl<<"Before Swap"<<endl;  cout<<endl<<"A="<<a<<"\t"<<"B="<<b;  cout<<endl<<"X="<<x<<"\t"<<"B="<<y;      swapp(a,b);   swapp(x,y);      cout<<endl<<endl<<"After Swap"<<endl;  cout<<endl<<"A="<<a<<"\t"<<"B="<<b;  cout<<endl<<"X="<<x<<"\t"<<"B="<<y;       return 0;}
Before Swap

A=10    B=20
X=20.3    B=55.3

After Swap

A=20    B=10
X=55.3    B=20.3
Note:  Apart from built-in data types like int, double, char etc, the template parameter ‘T’ can also be replaced by user defined data type.
An Example Program for function template specialization For example, consider the following simple code where we have general template fun() for all data types except int. For int, there is a specialized version of fun().  
CPP
#include <iostream>using namespace std; template <class T>void fun(T a){   cout << "The main template fun(): "        << a << endl;} template<>void fun(int a){    cout << "Specialized Template for int type: "         << a << endl;} int main(){    fun<char>('a');    fun<int>(10);    fun<float>(10.14);}
The main template fun(): a
Specialized Template for int type: 10
The main template fun(): 10.14
An Example Program for class template specialization In the following program, a specialized version of class Test is written for int data type.  
CPP
#include <iostream>using namespace std; template <class T>class Test{  // Data members of testpublic:   Test()   {       // Initialization of data members       cout << "General template object \n";   }   // Other methods of Test}; template <>class Test <int>{public:   Test()   {       // Initialization of data members       cout << "Specialized template object\n";   }}; int main(){    Test<int> a;    Test<char> b;    Test<float> c;    return 0;}
Specialized template object
General template object 
General template object 
How does template specialization work? When we write any template based function or class, compiler creates a copy of that function/class whenever compiler sees that being used for a new data type or new set of data types(in case of multiple template arguments). If a specialized version is present, compiler first checks with the specialized version and then the main template. Compiler first checks with the most specialized version by matching the passed parameter with the data type(s) specified in a specialized version. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
ashwinanil
aditiyadav20102001
cpp-template
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL