|
|
|
|
|
|
|
This tells the compiler that you are parameterizing this list on a type that you will define later, when you instantiate the list. For example, the declaration of the Node class now becomes |
|
|
|
|
|
|
|
|
template <class T>
class Node |
|
|
|
|
|
|
|
|
This indicates that Node will not exist as a class in itself, but rather that you will instantiate Nodes of Cats and Nodes of Data objects. The actual type you'll pass in is represented by T. |
|
|
|
|
|
|
|
|
Thus, InternalNode now becomes InternalNode<T> (read that as InternalNode of T). And InternalNode<T> points not to a Data object and another Node; rather, it points to a T (whatever type of object) and a Node<T>. You can see this on lines 118 and 119. |
|
|
|
|
|
|
|
|
Look carefully at Insert, defined on lines 133159. The logic is just the same, but where we used to have a specific type (Data) we now have T. Thus, on line 134 the parameter is a pointer to a T. Later, when we instantiate the specific lists, the T will be replaced by the compiler with the right type (Data or Cat). |
|
|
|
|
|
|
|
|
The important thing is that the InternalNode can continue working, indifferent to the actual type. It knows to ask the objects to compare themselves. It doesn't care whether Cats compare themselves in the same way Data objects do. In fact, we can rewrite this so that Cats don't keep their age; we can have them keep their birth date and compute their relative age on the fly, and the InternalNode won't care a bit. |
|
|
|
|
|
|
|
|
You can treat template items as you would any other type. You can pass them as parameters, either by reference or by value, and you can return them as the return values of functions, also by value or by reference. Listing 23.2 demonstrates how to pass Template objects. |
|
|
|
|
|
|
|
|
LISTING 23.2 DEMONSTRATING PARAMETERIZED LISTS |
|
|
|
 |
|
|
|
|
1: // ***********************************************
2: // FILE: Listing 23.2
3: //
4: // PURPOSE: Demonstrate parameterized list
5: // NOTES:
6: //
7: // COPYRIGHT: Copyright (C) 1997 Liberty Associates, Inc.
8: // All Rights Reserved
9: //
10: // Demonstrates an object-oriented approach to parameterized |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|