HP aC++/HP C A.06.25 Programmer's Guide

The compiler automatically substitutes the parameters you specified, in this case int
and 20, in place of the template formal parameters. You can create other instances of
this template using other built-in types as well as user-defined types.
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.
void 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.
180 Using HP aC++ Templates