Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
As illustrated in Volume 1, templates come in two flavors:
function templates and class templates. Both are wholly characterized by their
parameters. Each template parameter can represent one of the following:
1. Types
(either built-in or user-defined).
2. Compile-time
constant values (for example, integers, and pointers and references to static
entities; often referred to as non-type parameters).
3. Other
templates.
The examples in Volume 1 all fall into the first category
and are the most common. The canonical example for simple container-like
templates nowadays seems to be a Stack class. Being a container, a Stack
object is not concerned with the type of object it stores; the logic of holding
objects is independent of the type of objects being held. For this reason you
can use a type parameter to represent the contained type:
template<class T> class Stack {
T* data;
size_t count;
public:
void push(const T& t);
// Etc.
};
The actual type to be used for a particular Stack
instance is determined by the argument for the parameter T:
Stack<int> myStack; // A Stack of ints
The compiler then provides an int-version of Stack
by substituting int for T and generating the corresponding code.
The name of the class instance generated from the template in this case is Stack<int>.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |