×

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a data type sort() which is used everywhere in the code, and there is also a class called stack() which is used in every stack data type. There is a Quick shot class that is used for every data type except char. Let there is a big project where we need sort() for every data type, but if we use sort() for every data type, then it may affect the readability of the code. So to overcome this problem, C++ has a unique feature that we create special behaviour for a particular data type. This is called template specialization.

With the help of template specialization, we can use generic functions and generic classes in C++ programming, and it also provides the support of generic programming.

In C++, when we use a generic data type in an algorithm, then this programming is known as generic programming. With the help of generic programming, the same code is used in different ways.

Sometimes, we call Template as parameterized classes or functions.

Let us recall the concept of function overloading with the help of the below example.

Example 1:

#include<iostream>
using namespace std;


void show(int,int);
void show(double,double);
void show(char,char);


main()
{
 show(3,4);
 show(4.6,8.9);
 return 0;
}


void show(int p,int q)
{
 cout<<"p="<<p<<endl;
 cout<<"q="<<q<<endl;
}


void show(double p,double q)
{
 cout<<"p="<<p<<endl;
 cout<<"q="<<q<<endl;
}

Output:

Template Specialization in C++

When we carefully see the above code, we observe that the overloaded function in our program shows the disadvantages of the overloaded function. The disadvantage is each overloaded function performs the same work. But the difference is each overloaded function handles the different data type argument. So, it is a disadvantage for the C++ program. After knowing these disadvantages, a new concept came into existence in C++. This new concept is called “Function Template”. 

Function Template

With the help of a function template, we can write generic function in the C++ code that is not dependent on data type. We can also reduce the size of the code by using a function template. 

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.

Example 2:

#include<iostream>
using namespace std;


template<class X>
void show(X p,X q)
{
 cout<<"p="<<p<<endl;
 cout<<"q="<<q<<endl;
}


main()
{
 show(3,4);
 show(4.6,8.9);
 return 0;
}

Output:

Template Specialization in C++

Let us find the maximum of two values by using the function template.

Example 3:

#include<iostream>
using namespace std;


template<class Z>
void getMax(Z p,Z q)
{
 Z result;
 result=(p>q)?p:q;
 cout<<endl<<"Maximum Among Two is:"<<result;
}


main()
{
 getMax(4,7);
 getMax(3.6,8.6);
 getMax('H','L');
 return 0;
}

Output:

Template Specialization in C++

Example 4:

#include<iostream>
using namespace std;


template<class Z>
Z getMax(Z p,Z q)
{
 Z result;
 result=(p>q)?p:q;
 return result;
}


main()
{
int p=getMax(4,7);
double q=getMax(3.6,8.6);
cout<<endl<<p;
cout<<endl<<q;
 return 0;
}

Output:

Template Specialization in C++

Let us take an example of function template specialization. We take the fun() for the general Template.

Example 5:

#include <iostream>
using namespace std;


template <class Z>
void fun(Z p)
{
cout <<"The main template for fun(): "
 << p << endl;
}


template<>
void fun(int p)
{
 cout <<"Specialized Template for int type: "
 << p << endl;
}


int main()
{
 fun<char>('p');
 fun<int>(21);
 fun<float>(8.14);
}

Output:

Template Specialization in C++

Example of class template specialization

#include <iostream>
using namespace std;


template <class Z>
class Test
{


public:
Test()
{
 
 cout <<"It is a General template object \n";
}


};


template <>
class Test <int>
{
public:
Test()
{
 
 cout <<"It is a Specialized template object\n";
}
};


int main()
{
 Test<int> p;
 Test<char> q;
 Test<float> r;
 return 0;
}

Output:

Template Specialization in C++

How does template specialization work?

After writing any Template based class, the compiler just copies that function and then uses that function on a new data type. The compiler first checks whether there is any specialized version available or not. 


Related Topics

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.