C++ Tutorial: Function Templates

Function Templates
Function templates are used to reduce the repeated code. I want to make you clear about function templates by giving a small example here. Functions abs() and fabs() are used to find the absolute value or non-negative value of a integer and floating point variable respectively. To calculate the absolute value of integer and floating point variable, we need to call two different functions. And they are defined differently with almost same code except for data types. In case of function call, if we want absolute value of –2 then we need to call abs() function and to calculate the value of –6.6 we need to call fabs() function and function definition for both of them must be different. This shows that there is redundancy in coding for both function call and function definition. One important question arises here and that is “Can I use only one function call and only one function definition to calculate absolute value of both integer and floating point??”. The simple answer for this question is YES you can by the use of function template. Note that: only one function call can be made to call both the function by using function overloading but the problem of different function definition is still unsolved. Let us explore this idea by considering another example with source code:
#include <iostream>

using namespace std;

int find_max(int a, int b){

int result;

if(a > b)

result = a;

else

result = b;

}

float find_max(float a, float b){

float result;

if(a > b)

result = a;

else

result = b;

return result;

}

int main(){

int a = 5, b = 6;

float x = 2.7, y = 9.3;

cout<<"The greater between a and b is "<<find_max(a,b)<<endl;

cout<<"The greater between x and y is "<<find_max(x,y);

return 0;

}



In above example although same function call find_max() is used to call both integer and floating point, two different function definitions must be written in order call functions. So by the use of function template you can avoid this problem.

#include <iostream>

using namespace std;

template <class T>

T find_max(T a, T b){

T result;

if(a > b)

result = a;

else

result = b;

return result;

}

int main(){

int a = 5, b = 6;

float x = 2.7, y = 9.3;

cout<<"The greater between a and b is "<<find_max(a,b)<<endl;

cout<<"The greater between x and y is "<<find_max(x,y);

return 0;

}

SHARE C++ Tutorial: Function Templates