HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)
use a template, you provide the particular types or constant expressions as actual
parameters thereby creating a particular object or function.
Class Templates
A class template defines a family of classes. To declare a class template, you use the
keyword template followed by the template’s formal parameters. Class templates can
take parameters that are either types or expressions. You define a template class in terms
of those parameters. For example, the following is a class template for a simple stack
class. The template has two parameters, the type specifier T and the int parameter
size. The keyword class in the < > brackets is required to declare any template type
parameters. The first parameter T is used for the stack element type. The second parameter
is used for the maximum size of the stack.
template<class T, int size>
class Stack
{
public:
Stack(){top=-1;}
void push(const T& item){thestack[++top]=item;}
T& pop(){return thestack[top--];}
private:
T thestack[size];
int top;
};
Class template member functions and member data use the formal parameter type, T,
and the formal parameter expression, size. When you declare an instance of the class
Stack, you provide an actual type and a constant expression. The object created uses
that type and value in place of T and size, respectively.
For example, the following program uses the Stack class template to create a stack of
20 integers by providing the type int and the value 20 in the object declaration.
int main()
{ Stack<int,20> myintstack;
int i;
myintstack.push(5);
myintstack.push(56);
myintstack.push(980);
myintstack.push(1234);
i = myintstack.pop();
}
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.
Invoking Compile-Time Instantiation 169