What is function template?
- Function template defines a general set of operations that will be applied to various types of data. The type of data that the function will operate upon is passed to it as a parameter. Through a generic function, a single general procedure can be applied to a wide range of data. Depending on the program, the compiler creates different versions of function template associated with different data types. Generic function is created using the keyword template. It is used to create a template that describes what a function will do. E.g. we can write a function template that swaps two numbers. We can use the same template to swap two ints, two floats or even two chars.
- Consider the following example :
#include <iostream>
template <class X> void swap(X &a, X &b) // ? Function template
{
X temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int i = 10, j = 20;
float x = 4.5, y = 8.7;
char a = ‘A’, b = ‘B’;
cout << “Original i and j are : “<< i << ‘ ‘ << j << ‘\n’;
cout << “Original x and y are : “<< x << ‘ ‘ << y << ‘\n’;
cout << “Original a and b are : “<< a << ‘ ‘ << b << ‘\n’;
swap(i, j); // we can call the same function with different parameters
swap(x, y); // Compiler has created 3 version of template function
swap(a, b); //The correct version will be called depending on parameters passed
cout << “Swapped i and j are : “<< i << ‘ ‘ << j << ‘\n’;
cout << “Swapped x and y are : “<< x << ‘ ‘ << y << ‘\n’;
cout << “Swapped a and b are : “<< a << ‘ ‘ << b << ‘\n’;
return 0;
}