Chap. 6 Function Templates
Can be considered, whenever you write several identical functions that
perform the same operation on different data types. (cf. Function Overloading)
A function that returns the absolute value of a integer number
int abs(int n)
{
return (n < 0) ? -n : n;
}
A function that returns the absolute value of a float number
float abs(float n)
{
return (n < 0) ? -n : n;
}
...
Using a Function Template
// template used for absolute value function
#include <iostream.h>
template <class T> // function template
T abs(T n)
{
return (n < 0) ? -n : n;
}
void main()
{
int int1 = 5;
int int2 = -6;
long lon1 = 70000L;
long lon2 = -80000;
double dub1 = -9e-2;
double dub2 = -10.15;
cout << abs(int1) << endl;
cout << abs(int2) << endl;
cout << abs(lon1) << endl;
cout << abs(lon2) << endl;
cout << abs(dub1) << endl;
cout << abs(dub2) << endl;
}