A function template lets you parameterize a data type. The reason this is referred to as generic programming is that a single template function will support many built-in and user-defined data types. A templatized function works like a C-style macro, except for the fact that the C++ compiler will type check the function when we supply an incompatible data type at the time of invoking the template function.
It will be easier to understand the template concept with a simple example, as follows:
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
template <typename T, int size>
void sort ( T input[] ) {
for ( int i=0; i<size; ++i) {
for (int j=0; j<size; ++j) {
if ( input[i] < input[j] )
swap (input[i], input[j] );
}
}
}
int main () {
int a[10] = { 100, 10, 40, 20, 60, 80, 5, 50, 30, 25 };
cout << "\nValues in the int array before sorting ..." << endl;
copy ( a, a+10, ostream_iterator<int>( cout, "\t" ) );
cout << endl;
::sort<int, 10>( a );
cout << "\nValues in the int array after sorting ..." << endl;
copy ( a, a+10, ostream_iterator<int>( cout, "\t" ) );
cout << endl;
double b[5] = { 85.6d, 76.13d, 0.012d, 1.57d, 2.56d };
cout << "\nValues in the double array before sorting ..." << endl;
copy ( b, b+5, ostream_iterator<double>( cout, "\t" ) );
cout << endl;
::sort<double, 5>( b );
cout << "\nValues in the double array after sorting ..." << endl;
copy ( b, b+5, ostream_iterator<double>( cout, "\t" ) );
cout << endl;
string names[6] = {
"Rishi Kumar Sahay",
"Arun KR",
"Arun CR",
"Ninad",
"Pankaj",
"Nikita"
};
cout << "\nNames before sorting ..." << endl;
copy ( names, names+6, ostream_iterator<string>( cout, "\n" ) );
cout << endl;
::sort<string, 6>( names );
cout << "\nNames after sorting ..." << endl;
copy ( names, names+6, ostream_iterator<string>( cout, "\n" ) );
cout << endl;
return 0;
}
Run the following commands:
g++ main.cpp -std=c++17
./a.out
The output of the preceding program is as follows:
Values in the int array before sorting ...
100 10 40 20 60 80 5 50 30 25
Values in the int array after sorting ...
5 10 20 25 30 40 50 60 80 100
Values in the double array before sorting ...
85.6d 76.13d 0.012d 1.57d 2.56d
Values in the double array after sorting ...
0.012 1.57 2.56 76.13 85.6
Names before sorting ...
Rishi Kumar Sahay
Arun KR
Arun CR
Ninad
Pankaj
Nikita
Names after sorting ...
Arun CR
Arun KR
Nikita
Ninad
Pankaj
Rich Kumar Sahay
Isn't it really interesting to see just one template function doing all the magic? Yes, that's how cool C++ templates are!
Are you curious to see the assembly output of a template instantiation? Use the command, g++ -S main.cpp.