Open In App

Template Specialization in C++

Last Updated : 26 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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;
}


Output

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 function
template <class T>
void sort(T arr[], int size)
{
    // code to implement Quick Sort
}
 
// Template Specialization: A function
// specialized for char data type
template <>
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 TEMPLATE:-

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;
}


Output

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;
}


Output

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;
}


Output

5
7.6

C++




// create a function template that prints the swap of two numbers.
 
#include<iostream>
using namespace std;
 
template<class T>
void swap(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;
   
   swap(a,b);
   swap(x,y);
    
  cout<<endl<<endl<<"After Swap"<<endl;
  cout<<endl<<"A="<<a<<"\t"<<"B="<<b;
  cout<<endl<<"X="<<x<<"\t"<<"B="<<y;
   
    return 0;
}


Output

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);
}


Output

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 test
public:
   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;
}


Output

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. 

 



Previous Article
Next Article

Similar Reads

Partial Template Specialization in C++
In C++, template specialization enables us to define specialized versions of templates for some specific argument patterns. It is of two types: Full Template SpecializationPartial Template SpecializationIn this article, we will discuss the partial template specialization in C++ and how it is different from the full template specialization Partial T
3 min read
The C++ Standard Template Library (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequ
5 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
is_rvalue_reference Template in C++
The std::is_rvalue_reference template of C++ STL is used to check whether the type is a rvalue reference type or not. It returns a boolean value showing the same. Syntax: template &lt;class T &gt; struct is_rvalue_reference; Parameters: This template accepts a single parameter T (Trait class) to check whether T is a rvalue reference type. Return Va
2 min read
is_fundamental Template in C++
The is_fundamental template of C++ STL is used to check whether the type is a fundamental type or not. It returns a boolean value showing the same. Syntax: template &lt;class T&gt; struct is_fundamental; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a fundamental type or not. Return Value: This template r
2 min read
is_pointer Template in C++
The std::is_pointer template of C++ STL is used to check whether the given type is pointer or not. It returns a boolean value showing the same. Syntax: template &lt;class T &gt; struct is_pointer; Parameter: This template accepts a single parameter T (Trait class) to check whether T is a pointer or not. Return Value: This template returns a boolean
2 min read
generate_canonical Function template in C++
This template in C++ is used to convert the value generated by g into a floating point value in the range [0, 1) preserving the uniformity properties of sequences generated with g. To generate enough entropy generate_canonical() will call g() exactly 'k' times where, [Tex] k = max(1, \lceil \frac{b}{log_2 R} \rceil)[/Tex] Syntax: template ( class R
2 min read
std is_union() template in C++
The std::is_union template of C++ STL is used to check whether the given type is union or not. It returns a boolean value showing the same. Syntax: template &lt;class T&gt; struct is_union; Parameter: This template accepts single parameter T (Trait class) to check whether T is a union or not. Return Value: This template returns a boolean value as s
2 min read
is_class template in C++
The std::is_class template of C++ STL is used to check whether the given type is class or not. It returns a boolean value showing the same. Syntax: template &lt;class T&gt; struct is_class; Parameter: This template accepts single parameter T (Trait class) to check whether T is a class or not. Return Value: This template returns a boolean value as s
2 min read
std::is_enum Template in C++
The std::is_enum template of C++ STL is used to check whether the given type is enum or not. It returns a boolean value showing the same. Syntax: template &lt;class T&gt; struct is_enum; Parameter: This template accepts single parameter T (Trait class) to check whether T is a enumeration type or not. Return Value: This template returns a boolean va
2 min read
Article Tags :
Practice Tags :