Sams Teach Yourself C++ in 21 Days

(singke) #1
The definition of the template determines the parameterized type. Each instance of the
template is an actual object, which can be used like any other object—as a parameter to a
function, as a return value, and so forth.
Template classes can also declare three types of friend functions: nontemplate, general
template, and type-specific template. A template can declare static data members, in
which case each instance of the template has its own set of static data.
If you need to specialize behavior for some template functions based on the actual type,
you can override a template function with a particular type. This works for member func-
tions as well.
In the second half of today’s lesson, you learned that the C++ standard includes informa-
tion on the Standard Template Library (STL). The STL includes numerous template and
operations for you to use.

Q&A ....................................................................................................................


Q Why use templates when macros will do?
A Templates are type-safe and built in to the language, so they are checked by the
compiler—at least when you instantiate the class to create a particular variable.
Q What is the difference between the parameterized type of a template function
and the parameters to a normal function?
A A regular function (nontemplate) takes parameters on which it can take action. A
template function enables you to parameterize the type of a particular parameter to
the function. That is, you can pass an Arrayof Typeto a function and then have
the Typedetermined by the definition of the variable that is an instance of the class
for a specific type.
Q When do I use templates and when do I use inheritance?
A Use templates when all the behavior, or virtually all the behavior, is unchanged,
except in regard to the type of the item on which your class acts. If you find your-
self copying a class and changing only the type of one or more of its members, it
might be time to consider using a template. Also, use a template when you are
tempted to change a class to operate on a higher-level ancestor class (reducing
type-safety) of its operands, or to make two unrelated classes share a common
ancestor so that your class can work with both of them (again, reducing type-
safety).

712 Day 19

Free download pdf