HP aC++/HP C A.06.20 Programmer's Guide
NOTE: This example is not meant to account for all cases of changed behavior.
C++ Template Tutorial
You can create class templates and function templates. A template defines a group of
classes or functions. A template can have one or more types as parameters. When you
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.
void main()
{ Stack<int,20> myintstack;
int i;
myintstack.push(5);
myintstack.push(56);
myintstack.push(980);
myintstack.push(1234);
i = myintstack.pop();
}
Invoking Compile-Time Instantiation 175