Function Templates

A function template specifies a family of functions. Unlike class templates, to cause the generation of a particular function, the specification of the parameters of a function template is not required; rather, function overloading resolution can be used to select implicitly and generate a function.


template<class T> T maximum(T a, T b); // Declaration of function template.
template<class T> T maximum(T a, T b)  // Definition of function template.
{return a>b ? a : b;};
int maximum(int i, int j)              // Specific version of maximum.
{return i>j ? i : j;}
int i=1,j=2;
int k = maximum(i,j);                  // Uses specific version of maximum
double f=1,g=2;
double h = maximum(f,g);               // Generates a function maximum that
                                       // accepts two doubles and returns a double.


Overloading Resolution for Template Functions

A template function may be overloaded by other functions of the same name or by other template functions of the same name. The following three steps are used when resolving a call involving overloaded template functions.

  1. A search for an exact match is conducted. If the search is successful then the resultant function is called.

  2. The existence a function template that is capable of providing an exact match (excluding even trivial conversions) is determined. If such a function template exists then it is used to generate and call the function.

  3. Standard function overloading resolution is used to obtain a function that may be called.

If in any step, multiple functions can be found to match the call then it is ambiguous. If all of the above steps fail to locate an appropriate function then the call is in error. Pointers to functions are matched in precisely the same way as described above.


The following examples illustrate the point that a function template must use each template parameter in the declaration of the function contained therein.

template<class T>  T* f();  // error - T used in return but not in parameter list.
template<class T>
void g()                    // error - again T not used in parameter list.
  T tinst;
template<class U, class V> void h(U*,V&);   // Correct - both U and V used in parameter list.