|
|
|
|
|
|
|
In this example, the keyword class is used, followed by the identifier T. The keyword class indicates that this parameter is a type. The identifier T is used throughout the rest of the template definition to refer to the parameterized type. One instance of this class will substitute int everywhere T appears, and another will substitute Cat. |
|
|
|
|
|
|
|
|
To declare an int and a Cat instance of the parameterized list class, you would write |
|
|
|
|
|
|
|
|
List<int> anIntList;
List<Cat> aCatList; |
|
|
|
|
|
|
|
|
The object anIntList is of the type list of integers; the object aCatList is of the type ListOfCats. You can now use the type List<int> anywhere you would normally use a typeas the return value from a function, as a parameter to a function, and so forth. |
|
|
|
|
|
|
|
|
Listing 23.1 parameterizes our List object. This is an excellent technique for building templates: Get your object working on a single type, as we did in Lesson 19, Linked Lists. Then by parameterizing, generalize your object to handle any type. |
|
|
|
|
|
|
|
|
LISTING 23.1 DEMONSTRATING PARAMETERIZED LISTS |
|
|
|
 |
|
|
|
|
1: // ***********************************************
2: // FILE: Listing 23.1
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
11: // linked lists. The list delegates to the node.
12: // The node is an abstract Object type. Three types of
13: // nodes are used, head nodes, tail nodes and internal
14: // nodes. Only the internal nodes hold Object.
15: //
16: // The Object class is created to serve as an object to
17: // hold in the linked list.
18: //
19: // ***********************************************
20:
21:
22: #include <iostream.h>
23:
24: enum { kIsSmaller, kIsLarger, kIsSame};
25:
26: // Object class to put into the linked list
27: // Any class in this linked list must support two methods: |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|