template
bool Stack
{
...
}
If you define a method within the class declaration (an inline definition), you can omit the template preface and the class qualifier.
Listing 14.13 shows the combined class and member function templates. It’s important to realize that these templates are not class and member function definitions. Rather, they are instructions to the C++ compiler about how to generate class and member function definitions. A particular actualization of a template, such as a stack class for handling string objects, is called an
Listing 14.13. stacktp.h
// stacktp.h -- a stack template
#ifndef STACKTP_H_
#define STACKTP_H_
template
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Type items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item); // add item to stack
bool pop(Type & item); // pop top into item
};
template
Stack
{
top = 0;
}
template
bool Stack
{
return top == 0;
}
template
bool Stack
{
return top == MAX;
}
template
bool Stack
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
template
bool Stack
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
#endif
Using a Template Class
Merely including a template in a program doesn’t generate a template class. You have to ask for an instantiation. To do this, you declare an object of the template class type, replacing the generic type name with the particular type you want. For example, here’s how you would create two stacks, one for stacking ints and one for stacking string objects:
Stack
Stack
Seeing these two declarations, the compiler will follow the Stack
Generic type identifiers such as Type in the example are called
Notice that you have to provide the desired type explicitly. This is different from ordinary function templates, for which the compiler can use the argument types to a function to figure out what kind of function to generate:
template
void simple(T t) { cout << t << '\n';}
...
simple(2); // generate void simple(int)
simple("two"); // generate void simple(const char *)
Listing 14.14 modifies the original stack-testing program (Listing 10.12) to use string purchase order IDs instead of unsigned long values.
Listing 14.14. stacktem.cpp
// stacktem.cpp -- testing the template stack class
#include
#include
#include
#include "stacktp.h"
using std::cin;
using std::cout;
int main()
{
Stack
char ch;
std::string po;
cout << "Please enter A to add a purchase order,\n"