Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 669

19


the class name. You have declared your type parameter to be Ton line 53, so for the
Arrayclass, you use Array<T>with your member functions. You see this on line 55.
Within the member function, you can then use the Tparameter anywhere you would have
ordinarily used the type of the array. For example, on line 58 the class’ pointer,pType,is
set to point to a new array of items. The items will be of type T, which is the type you
declare when instantiating an object with this template class. When each item of a given
type is created, its construction should initialize it.
You see this same process repeated with the declaration of the copy constructor on lines
64–71 and the overloading of the equals operator on lines 74–85.
Your Arraytemplate class is actually used on lines 90 and 91. On line 90, it is used to
instantiate an object called theArraythat uses the template with ints. On line 91,
theZoois instantiated to be an Arrayof type Animal.
The rest of the listing does what was described earlier and is pretty easy to follow.

Passing Instantiated Template Objects to Functions ..........................................


If you want to pass an Arrayobject to a normal function, you must pass a particular
instance of the array, not a template. To create a function that can receive a specific
instance of an Array, you declare the type as follows:
void SomeFunction(Array<theType>&);
where SomeFunctionis the name of the function you are passing the Arrayobject to, and
theTypeis the type of the object you are creating. Therefore, if SomeFunction()takes an
integer array as a parameter, you can write
void SomeFunction(Array<int>&); // ok
but you cannot write
void SomeFunction(Array<T>&); // error!
because there is no way to know what a T&is. You also cannot write
void SomeFunction(Array &); // error!
because there is no class Array—only the template and the instances.
To create nonmember functions that have some of the advantages of templates, you can
declare a template function. This is accomplished in a similar manner to declaring a
Free download pdf