Working with Function Templates

OverviewHow Do I

With function templates, you can specify a set of functions that are based on the same code, but act on different types or classes. For example:

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

This code defines a family of functions that swap their parameters. From this template you can generate functions that will swap not only int and long types, but also user-defined types. MySwap will even swap classes if the class’s copy constructor and assignment operator are properly defined.

In addition, the function template will prevent you from swapping objects of different types, because the compiler knows the types of the a and b parameters at compile time.

You call a function template function as you would a normal function; no special syntax is needed. For example:

int i, j;
char k;
MySwap( i, j );     //OK
MySwap( i, k );     //Error, different types.

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.

What do you want to know more about?