Function Templates

Class templates define a family of related classes that are based on the parameters passed to the class upon instantiation. Function templates are similar to class templates, but define a family of functions. Here is a function template that swaps two items:

template< class T > void MySwap( T& a, T& b )
{
   T c;
   c = a; a = b; b = c;
}

Although this function could be performed by a nontemplated function, using void pointers, the template version is type-safe. Consider the following calls:

int j = 10;
int k = 18;
CString Hello = "Hello, Windows!";
MySwap( j, k );          //OK
MySwap( j, Hello );      //error

The second MySwap call triggers a compile-time error, since the compile cannot generate a MySwap function with parameters of different types. If void pointers were used, both function calls would compile correctly, but the function would not work properly at run time.

Explicit specification of the template arguments for a function template is allowed. For example:

template<class T> void f(T) {...}
void g(char j) {
   f<int>(j);   //generate the specialization f(int)
}

When the template argument is explicitly specified, normal implicit conversions are done to convert the function argument to the type of the corresponding function template parameters. In the above example, the compiler will convert (char j) to type int.