×

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

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 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.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

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++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.