Template Specialization in C++
Last Updated :
26 Aug, 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++
#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
template <class T>
void sort(T arr[], int size)
{
}
template <>
void sort<char>(char arr[], int size)
{
}
|
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++
#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++
#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++
#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;
}
|
C++
#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
{
public:
Test()
{
cout << "General template object \n";
}
};
template <>
class Test <int>
{
public:
Test()
{
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.
Similar Reads
C++ STL Algorithm Library
Standard Template Library (STL) offers a rich collection of algorithms designed to operate on STL containers and beyond. It provides commonly used algorithms such as sorting, searching, copying, etc. These well tested algorithms are optimized for performance and provide a way to write cleaner, faste
4 min read
sort() in C++ STL
In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structures that provide random access to its elements such as vectors and arrays. Let's take a look at an example: [GFGTABS] C
4 min read
Type Inference in C++ (auto and decltype)
Type Inference refers to automatic deduction of the data type of an expression in a programming language. Before C++ 11, each data type needed to be explicitly declared at compile-time, limiting the values of an expression at runtime but after the new version of C++, keywords such as auto and declty
6 min read
transform() in C++ STL
In C++, transform() is a built-in STL function used to apply the given operation to a range of elements and store the result in another range. Letâs take a look at a simple example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main() {
4 min read
Variadic function templates in C++
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor
3 min read
Template Specialization in C++
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 p
5 min read
Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge,
Some of the merge operation classes are provided in C++ STL under the header file "algorithm", which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container
7 min read
std::partition in C++ STL
C++ has a class in its STL algorithms library which allows us easy partition algorithms using certain inbuilt functions. Partition refers to act of dividing elements of containers depending upon a given condition. Partition operations :1. partition(beg, end, condition) :- This function is used to pa
5 min read
accumulate() and partial_sum() in C++ STL
accumulate() and partial_sum() functions are used to find the sum or any other accumulated value that is obtained by doing the addition or any other binary operation on the elements in the given range. Both of these functions are the part of STL Numeric Library and defined inside <numeric> hea
4 min read
numeric header in C++ STL | Set 2 (adjacent_difference(), inner_product() and iota())
The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header: iotaaccumulatereduceinner_productpartial_sum etc.
4 min read