|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Template
Functions
|
|
|
|
|
|
|
|
* |
|
We
can also produce functions that have template parameters. This allows us
to write functions that can take a wide range of parameter types that are
generic to the function definition
For example, we could write
a simple swap procedure for any type of data: |
|
|
|
* |
|
|
|
|
template
< class T>
void
swap(T&a,
T&b)
{
Tt;
t
= a;
a
= b;
b
= t;
}; |
|
|
|
|
|
|
* |
|
Whenever
we call swap the compiler will examine the types of its parameters and
then generate the appropriate version of the swap procedure, if it hasn't
already been generated
Examples:
int
i, j;
double
x, y; |
|
|
|
|
* |
|
|
|
|
|
|
|
swap(i,
j); swap(x, y); swap(i, x); |
|
//
generate swap(int, int)
//
generate swap(double, double)
//
error, both parameters to swap |
|
|
|