template <class T> // declare the template and the parameter
class Array // the class being parameterized
{
public:
Array();
// full class declaration here
};
This code is the basics for declaring a template class called Array. The keyword
templateis used at the beginning of every declaration and definition of a template
class. The parameters of the template are after the keyword template. Like with
functions, the parameters are the things that will change with each instance. In the
array template being created in the preceding example, you want the type of the objects
stored in the array to be changeable. One instance might store an array of integers and
another might store an array of Animals.
In this example, the keyword classis used, followed by the identifier T. As stated
before, the keyword classindicates that this parameter is a type. The identifier Tis used
throughout the rest of the template definition to refer to the parameterized type. Because
this class is now a template, one instance could substitute intfor Tand one could substi-
tute the type Cat. If written correctly, the template should be able to accept any valid
data type (or class) as the value for T.
You set the type for your template when you declare a variable that will be an instance of
it. This can be done using the following format:
className<type> instance;
In this case,classNameis the name of your template class. instanceis the name of the
instance, or object, you are creating. typeis exactly that—the data type you want to use
for the instance you are creating.
For example, to declare an intand an Animalsinstance of the parameterized Array
class, you would write:
Array<int> anIntArray;
Array<Animal> anAnimalArray;
The object anIntArrayis of the type array of integers; the object anAnimalArrayis of
the type array of Animals. You can now use the type Array<int>anywhere you would
normally use a type—as the return value from a function, as a parameter to a function,
and so forth. To help bring some this together for you, Listing 19.1 provides the full dec-
laration of the stripped-down Arraytemplate. Be aware that this isn’t a complete pro-
gram, rather a listing focused on how the template is defined.
662 Day 19