TOPIC 14.2.1
Templates
Template functions may be overloaded in the following two ways. The template function can be overloaded by another funtion which is not a template. It can also be overloaded by another template function with the same name using different parameters. By overloading template functions it is easier to provide a function witch can be used in many different ways, while being able to control how the function will react when using different data types, and different parameters. The example below shows the two different types of template function overloading.
#include <iostream.h>
template <class DataType>
void swap(DataType & x, DataType & y);
//could be used to round floats to
//the nearest int when they are swapped
void swap(float & x, float & y);
//would be used to swap three datatypes
template <class DataType>
void swap(DataType & x, DataType & y, DataType & z);
int main()
{
int a = 1,
b = 2;
float c = 1.2345,
d = 9.8765;
char String1[] = "This is string one.";
char String2[] = "This is string two!";
cout << "a is " << a << ", b is " << b << endl;
swap(a,b);
cout << "a is " << a << ", b is " << b << endl << endl;
cout << "c is " << c << ", d is " << d << endl;
swap(c,d);
cout << "c is " << c << ", d is " << d << endl << endl;
cout << "String1: " << String1 << endl
<< "String2: " << String2 << endl;
swap(String1[18],String2[18]);
cout << "String1: " << String1 << endl
<< "String2: " << String2 << endl;
return 0;
}
template <class DataType>
void swap(DataType & x, DataType & y)
{
DataType temp = x;
x = y;
y = temp;
}
void swap(float & x, float & y)
{
int temp = x;
x = floor(y + .5); //rounds to the nearest integer
y = floor(temp + .5); //rounds to the nearest integer
}
template <class DataType>
void swap(DataType & x, DataType & y, DataType & z)
{
DataType temp = x;
x = y;
y = z;
z = temp;
}