HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)

Function Templates
A function template defines a family of functions. To declare a function template, use the
keyword template to define the formal parameters, which are types, then define the
function in terms of those types. For example, the following is a function template for a
swap function. It simply swaps the values of its two arguments:
template<class T>
void swap(T& val1, T& val2)
{
T temp=val1;
val1=val2;
val2=temp;
}
The argument types to the function template swap are not specified. Instead, the formal
parameter, T, is a placeholder for the types. To use the function template to create an
actual function instance (a template function), you simply call the function defined by the
template and provide actual parameters. A version of the function with those parameter
types is created (instantiated).
For example, the following main program calls the function swap twice, passing int
parameters in the first case and float parameters in the second case. The compiler
uses the swaptemplate to automatically create two versions, or instances, of swap, one
that takes int parameters and one that takes float parameters.
int main()
{ int i=2, j=9;
swap(i,j);
float f=2.2, g=9.9;
swap(f,g);
}
Other versions of swap can be created with other types to exchange the values of the
given type.
170 Using HP aC++ Templates