Working with C++ Functions


Tired of defining five times the same function? One definition for int type parameters, one definition for double type parameters, one definition for float type parameters... Didn't you forget one type? What if a new data type is used? No problem: the C++ compiler is capable of generating automatically every version of the function that is necessary! Just tell him how the function looks like by declaring a template function: 

#include <iostream.h>

template <class ttype>
ttype min (ttype a, ttype b)
{
ttype r;

r = a;
if (b < a) r = b;

return r;
}

void main ()
{
int i1, i2, i3;

i1 = 34;
i2 = 6;
i3 = min (i1, i2);
cout << "Most little: " << i3 << endl;

double d1, d2, d3;

d1 = 7.9;
d2 = 32.1;
d3 = min (d1, d2);
cout << "Most little: " << d3 << endl;

cout << "Most little: " << min (d3, 3.5) << endl;
}

The function min is used three times in above program yet the C++ compiler generates only two versions of it: int min (int a, int b) and double min (double a, double b). That does the job for the whole program. 
Would you have tried something like calculating min (i1, d1) the compiler would have reported that as an error. Indeed the template tells both parameters are of the same type. 

You can use a random number of different template data types in a template definition. And not all parameter types must be templates, some of them can be of standard types or user defined (char, int, double...). Here is an example where the min function takes parameters of any, possibly different, types and outputs a value that has the type of the first parameter: 

#include <iostream.h>

template <class type1, class type2>
type1 min (type1 a, type2 b)
{
type1 r, b_converted;
r = a;
b_converted = (type1) b;
if (b_converted < a) r = b_converted;
return r;
}

void main ()
{
int i;
double d;

i = 45;
d = 7.41;

cout << "Most little: " << min (i, d) << endl;
cout << "Most little: " << min (d, i) << endl;
cout << "Most little: " << min ('A', i) << endl;
}




Added on June 19, 2007 Comment
}