|
|
|
|
|
|
|
To solve this problem, you could create a List base class and derive from it the CarList and CatsList classes. You could then cut and paste much of the LinkedList class into the new CatsList declaration. Next week, however, when you want to make a list of Car objects, you have to make a new class and cut and paste again. |
|
|
|
|
|
|
|
|
Needless to say, this is not a satisfactory solution. Over time, the List class and its derived classes will have to be extended. Making sure that all the changes are propagated to all the related classes will then be a nightmare. |
|
|
|
|
|
|
|
|
Templates offer a solution to this problem. In addition, unlike old-fashioned macros, templates are an integrated part of the language, type-safe, and very flexible. |
|
|
|
|
|
|
|
|
Templates enable you to teach the compiler how to make a list of any type of thing, rather than creating a set of type-specific lists. A PartsList is a list of parts; a CatList is a list of cats. The only way in which they differ is the type of the thing on the list. With templates, the type of the thing on the list becomes a parameter to the definition of the class. |
|
|
|
|
|
|
|
|
New Term: The act of creating a specific type from a template is called instantiation, and the individual classes are called instances of the template. |
|
|
|
|
|
|
|
|
New Term: Templates provide you with the ability to create a general class and pass types as parameters to that class, to build specific instances. |
|
|
|
|
|
|
|
|
You declare a parameterized List object (a template for a list) by writing |
|
|
|
|
|
|
|
|
1: template <class T> // declare the template and the parameter
2: class List // the class being parameterized
3: {
4: public:
5: List();
6: // full class declaration here
7: }; |
|
|
|
|
|
|
|
|
The keyword template is used at the beginning of every declaration and definition of a template class. The parameters of the template are after the keyword template; they are the items that will change with each instance. For example, in the list template shown in the previous code snippet, the type of the objects stored in the list will change. One instance might store an list of Integers, while another might store an list of Animals. |
|
|
|
|
|