Sams Teach Yourself C++ in 21 Days

(singke) #1
when you want to make a list of Carobjects, you would then have to make a new class,
and again you would cut and paste.
Needless to say, this is not a satisfactory solution. Over time, you can expect the List
class and its derived classes will need to be extended. The task of making certain that all
the needed changes are propagated to all the related classes could quickly become a
nightmare.
Alternatively, you could inherit Catfrom Part, so that a cat could fit into the parts inher-
itance hierarchy, and so that a collection of parts could hold cats as well. Obviously, this
is a problem in terms of keeping a cleanly conceptual class hierarchy because cats are
not normally parts.
You could also create a Listclass that would contain something like “Object” and
inherit all objects from this base class. However, this relaxes strong typing and makes it
harder to have the compiler enforce correctness in your program. What you really want is
a way to create a family of related classes, whose only difference is the type of the thing
that they operate on; and you want to have only one place to make changes to that class
so that your maintenance effort can be kept low.
The creation and use of templates can solve these problems. Although templates were not
a part of the original C++ language, they are now a part of the standard and an integral
part of the language. Like all of C++, they are type-safe and very flexible. They can,
however, be intimidating to the newer C++ programmer. After you understand them,
however, you will see that they are a powerful feature of the language.
Templates enable you to create a class that can have the type of the things it works on be
changed. For example, you can use them to show the compiler how to make a list of any
type of thing, rather than creating a set of type-specific lists—a PartsListis a list of
parts; a CatsListis a list of cats. The only way in which they differ is the type of the
thing on the list. With templates, the typeof the thing on the list becomes a parameter to
the definition of the class. You can create a family of classes from the template, each of
which is set up to work on a different type of thing.
A common component of virtually all C++ libraries is an array class. You know it would
be tedious and inefficient to create one array class for integers, another for doubles, and
yet another for an array of Animals. Templates let you declare a single, parameterized
array class. You can then specify the type that the object will be for each instance of the
array.
Although the Standard Template Library provides a standardized set of containerclasses,
including arrays, lists, and so forth, the best way to learn about templates is to create
your own! In the next few sections, you’ll explore what it takes to write your template

660 Day 19

Free download pdf