Function Templates
The max( ) function template
The code for the functions
float max ( const float a, const float b );
int max ( const int a, const int b );
Rational max ( const Rational& a, const Rational& b);
myType max ( const myType& a, const myType& b);
is the same in all the functions and does not depend on the type
of data. We can write a function template that handles (almost) all
types of data and objects.
template
T max (const T& a, const T& b)
{
if ( a < b)
return b;
else
return a;
}
T is called the type parameter and can have any legal identifier name.
The compiler generates code
Note that in each example, the calling code doesn't "know"
about the function template. The template will not be used if the
compiler can find an exact match for the function being called.
max( ) for ints
When the compiler sees this code
int i1 = 1, i2 = 2, i3;
i3 = max(i1, i2);
it creates this function:
int max (const int& a, const int& b)
{
if (a < b)
return b;
else
return a;
}
max( ) for floats
When compiler sees this code:
float f1 = 1.2 f2 = 2.2, f3;
f3 = max(f1, f2);
it creates this function:
float max (const float& a, const float& b)
{
if (a < b)
return b;
else
return a;
}
max( ) for class Foo
When compiler sees this code:
Foo F1 = value1, F2 = value2, F3;
F3 = max(F1, F2);
it creates this function:
Foo max (const Foo& a, const Foo& b)
{
if (a < b)
return b;
else
return a;
}
Note that the Foo class must support the less than function ( operator< )
otherwise the line if ( a < b ) will generate a compiler
error
Beware of atypical cases
When the compiler sees this code:
char *str1 = "abc";
char *str2 = "def";
cout << max(str1, str2) << endl;
it creates this function:
char* max (const char*& a, const char*& b)
{
if (a < b)
return b;
else
return a;
}
Is this really what you want? What really gets compared?
This problem can be avoided by providing an explicit version
of max( ) for char pointers.
char* max(char *a, char *b)
{
if (strcmp(a,b) < 0)
return b;
else return a;
}
The compiler will find this exact match for the desired
function and not use the template.