📄 ch19.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<!-- This document was created from RTF source by rtftohtml version 3.0.1 -->
<META NAME="GENERATOR" Content="Symantec Visual Page 1.0">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">
<TITLE>Teach Yourself C++ in 21 Days</TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF">
<H1 ALIGN="CENTER"><A HREF="ch18.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch18.htm"><IMG SRC="BLANPREV.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANPREV.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="tppmsgs/msgs0.htm#1" tppabs="http://www.mcp.com/sams"><IMG
SRC="BLANHOME.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"
BORDER="0"></A><A HREF="index.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/index.htm"><IMG SRC="BLANTOC.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANTOC.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch20.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch20.htm"><IMG SRC="BLANNEXT.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANNEXT.GIF"
WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></H1>
<H1></H1>
<UL>
<LI><A HREF="#Heading1">Day 19</A>
<UL>
<LI><A HREF="#Heading2">Templates</A>
<UL>
<LI><A HREF="#Heading3">What Are Templates?</A>
<LI><A HREF="#Heading4">Parameterized Types</A>
<LI><A HREF="#Heading5">Template Definition</A>
<LI><A HREF="#Heading6">Listing 19.1. A template of an Array class</A><A HREF="#Heading7">.</A>
<UL>
<LI><A HREF="#Heading8">Using the Name</A>
<LI><A HREF="#Heading9">Implementing the Template</A>
</UL>
<LI><A HREF="#Heading10">Listing 19.2. The implementation of the template array</A><A
HREF="#Heading11">.</A>
<LI><A HREF="#Heading12">Template Functions</A>
<LI><A HREF="#Heading13">Templates and Friends</A>
<UL>
<LI><A HREF="#Heading14">Non-Template Friend Classes and Functions</A>
</UL>
<LI><A HREF="#Heading15">Listing 19.3. Non-template friend function</A><A HREF="#Heading16">.</A>
<UL>
<LI><A HREF="#Heading17">General Template Friend Class or Function</A>
</UL>
<LI><A HREF="#Heading18">Listing 19.4. Using operator ostream</A><A HREF="#Heading19">.</A>
<UL>
<LI><A HREF="#Heading20">A Type-Specific Template Friend Class or Function</A>
</UL>
<LI><A HREF="#Heading21">Using Template Items</A>
<LI><A HREF="#Heading22">Listing 19.5. Passing template objects</A>
<LI><A HREF="#Heading23">to and from functions.</A>
<UL>
<LI><A HREF="#Heading24">Specialized Functions</A>
</UL>
<LI><A HREF="#Heading25">Listing 19.6. Specializing template implementations</A><A
HREF="#Heading26">.</A>
<UL>
<LI><A HREF="#Heading27">Static Members and Templates</A>
</UL>
<LI><A HREF="#Heading28">Listing 19.7. Using static member data and functions</A>
<LI><A HREF="#Heading29">with templates.</A>
<LI><A HREF="#Heading30">The Standard Template Library</A>
<LI><A HREF="#Heading31">Summary</A>
<LI><A HREF="#Heading32">Q&A</A>
<LI><A HREF="#Heading33">Workshop</A>
<UL>
<LI><A HREF="#Heading34">Quiz</A>
<LI><A HREF="#Heading35">Exercises</A>
</UL>
</UL>
</UL>
</UL>
<P>
<HR SIZE="4">
<H2 ALIGN="CENTER"><A NAME="Heading1"></A><FONT COLOR="#000077">Day 19</FONT></H2>
<H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">Templates</FONT></H2>
<P>On Day 17, "The Preprocessor," you saw how to use macros to create various
lists using the concatenation operator. Macros have a number of problems that are
fixed by templates.</P>
<P>Today you will learn
<UL>
<LI>What templates are and how to use them.
<P>
<LI>Why templates supply a better alternative to macros.
<P>
<LI>How to create class templates.
<P>
<LI>How to create function templates.
</UL>
<H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">What Are Templates?</FONT></H3>
<P>At the end of Week 2, you saw how to build a <TT>PartsList</TT> object and how
to use it to create a <TT>PartsCatalog</TT>. If you want to build on the <TT>PartsList</TT>
object to make a list of cats, you have a problem: <TT>PartsList</TT> only knows
about parts.</P>
<P>To solve this problem, you can create a <TT>List</TT> base class and derive from
it the <TT>PartsList</TT> and <TT>CatsList</TT> classes. You could then cut and paste
much of the <TT>PartsList</TT> class into the new <TT>CatsList</TT> declaration.
Next week, when you want to make a list of <TT>Car</TT> objects, you would then have
to make a new class, and again you'd cut and paste.</P>
<P>Needless to say, this is not a satisfactory solution. Over time, the <TT>List</TT>
class and its derived classes will have to be extended. Making sure that all the
changes are propagated to all the related classes would be a nightmare.</P>
<P>On Day 17, one approach to parameterizing lists was demonstrated briefly--using
macros and name concatenation. Although macros do save much of the cutting and pasting,
they have one killer disadvantage: Like everything else in the preprocessor, they
are not type-safe.</P>
<P>Templates offer the preferred method of creating parameterized lists in C++. They
are an integrated part of the language, they are type-safe, and they are very flexible.
<H3 ALIGN="CENTER"><A NAME="Heading4"></A><FONT COLOR="#000077">Parameterized Types</FONT></H3>
<P>Templates allow 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 <TT>PartsList</TT> is a list
of parts, a <TT>CatList</TT> 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.</P>
<P>A common component of virtually all C++ libraries is an array class. As you saw
with <TT>Lists</TT>, it is tedious and inefficient to create one array class for
integers, another for doubles, and yet another for an array of <TT>Animal</TT>s.
Templates let you declare a parameterized array class and then specify what type
of object each instance of the array will hold.</P>
<DL>
<DD>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B><I>Instantiation</I> is the
act of creating a specific type from a template. The individual classes are called
instances of the template.
<HR>
</DL>
<P>Parameterized templates provide you with the ability to create a general class,
and pass types as parameters to that class, in order to build specific instances.
<H3 ALIGN="CENTER"><A NAME="Heading5"></A><FONT COLOR="#000077">Template Definition</FONT></H3>
<P>You declare a parameterized <TT>Array</TT> object (a template for an array) by
writing</P>
<PRE><FONT COLOR="#0066FF">1: template <class T> // declare the template and the parameter
2: class Array // the class being parameterized
3: {
4: public:
5: Array();
6: // full class declaration here
7: };
</FONT></PRE>
<P>The keyword <TT>template</TT> is used at the beginning of every declaration and
definition of a template class. The parameters of the template are after the keyword
<TT>template</TT>. The parameters are the things that will change with each instance.
For example, in the array template shown previously, the type of the objects stored
in the array will change. One instance might store an array of integers, while another
might store an array of <TT>Animals</TT>.</P>
<P>In this example, the keyword <TT>class</TT> is used, followed by the identifier
<TT>T</TT>. The keyword <TT>class</TT> indicates that this parameter is a type. The
identifier <TT>T</TT> is used throughout the rest of the template definition to refer
to the parameterized type. One instance of this class will substitute <TT>int</TT>
everywhere <TT>T</TT> appears, and another will substitute <TT>Cat</TT>.</P>
<P>To declare an <TT>int</TT> and a <TT>Cat</TT> instance of the parameterized <TT>Array</TT>
class, you would write</P>
<PRE><FONT COLOR="#0066FF">Array<int> anIntArray;
Array<Cat> aCatArray;
</FONT></PRE>
<P>The object <TT>anIntArray</TT> is of the type array of integers; the object <TT>aCatArray</TT>
is of the type array of cats. You can now use the type <TT>Array<int></TT>
anywhere you would normally use a type--as the return value from a function, as a
parameter to a function, and so forth. Listing 19.1 provides the full declaration
of this stripped-down <TT>Array</TT> template.
<BLOCKQUOTE>
<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Listing 19.1 is not a complete program!
<HR>
</BLOCKQUOTE>
<P><A NAME="Heading6"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 19.1. A template
of an Array class</B></FONT>
<PRE><FONT COLOR="#0066FF">1: Listing 19.1 A template of an array class
2: #include <iostream.h>
3: const int DefaultSize = 10;
4:
5: template <class T> // declare the template and the parameter
6: class Array // the class being parameterized
7: {
8: public:
9: // constructors
10: Array(int itsSize = DefaultSize);
11: Array(const Array &rhs);
12: ~Array() { delete [] pType; }
13:
14: // operators
15: Array& operator=(const Array&);
16: T& operator[](int offSet) { return pType[offSet]; }
17:
18: // accessors
19: int getSize() { return itsSize; }
20:
21: private:
22: T *pType;
23: int itsSize;</FONT><TT>
</TT><FONT COLOR="#0066FF"><TT>24: };</TT> </FONT>
</PRE>
<DL>
<DD>
<HR>
<FONT COLOR="#000077"><B>Output:</B></FONT><B> </B>There is no output. This is an
incomplete program.
<HR>
</DL>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The definition of the template
begins on line 5, with the keyword <TT>template</TT> followed by the parameter. In
this case, the parameter is identified to be a type by the keyword <TT>class</TT>,
and the identifier <TT>T</TT> is used to represent the parameterized type.</P>
<P>From line 6 until the end of the template on line 24, the rest of the declaration
is like any other class declaration. The only difference is that wherever the type
of the object would normally appear, the identifier <TT>T</TT> is used instead. For
example, <TT>operator[]</TT> would be expected to return a reference to an object
in the array, and in fact it is declared to return a reference to a <TT>T</TT>.</P>
<P>When an instance of an integer array is declared, the <TT>operator=</TT> that
is provided to that array will return a reference to an integer. When an instance
of an <TT>Animal</TT> array is declared, the <TT>operator=</TT> provided to the <TT>Animal</TT>
array will return a reference to an <TT>Animal</TT>.
<H4 ALIGN="CENTER"><A NAME="Heading8"></A><FONT COLOR="#000077">Using the Name</FONT></H4>
<P>Within the class declaration, the word <TT>Array</TT> may be used without further
qualification. Elsewhere in the program, this class will be referred to as <TT>Array<T></TT>.
For example, if you do not write the constructor within the class declaration, you
must write</P>
<PRE><FONT COLOR="#0066FF">template <class T>
Array<T>::Array(int size):
itsSize = size
{
pType = new T[size];
for (int i = 0; i<size; i++)
pType[i] = 0;
}
</FONT></PRE>
<P>The declaration on the first line of this code fragment is required to identify
the type (<TT>class T</TT>). The template name is <TT>Array<T></TT>, and the
function name is <TT>Array(int size)</TT>.</P>
<P>The remainder of the function is exactly the same as it would be for a non-template
function. It is a common and preferred method to get the class and its functions
working as a simple declaration before turning it into a template.
<H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">Implementing the
Template</FONT></H4>
<P>The full implementation of the <TT>Array</TT> template class requires implementation
of the copy constructor, <TT>operator=</TT>, and so forth. Listing 19.2 provides
a simple driver program to exercise this template class.
<DL>
<DD>
<HR>
<FONT COLOR="#000077"><B><BR>
NOTE:</B></FONT><B> </B>Some older compilers do not support templates. Templates
are, however, part of the emerging C++ standard. All major compiler vendors have
committed to supporting templates in their next release, if they have not already
done so. If you have an older compiler, you won't be able to compile and run the
exercises in this chapter. It's still a good idea to read through the entire chapter,
however, and return to this material when you upgrade your compiler.
<HR>
</DL>
<P><A NAME="Heading10"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 19.2. The implementation
of the template array.</B></FONT>
<PRE><FONT COLOR="#0066FF">1: #include <iostream.h>
2:
3: const int DefaultSize = 10;
4:
5: // declare a simple Animal class so that we can
6: // create an array of animals
7:
8: class Animal
9: {
10: public:
11: Animal(int);
12: Animal();
13: ~Animal() {}
14: int GetWeight() const { return itsWeight; }
15: void Display() const { cout << itsWeight; }
16: private:
17: int itsWeight;
18: };
19:
20: Animal::Animal(int weight):
21: itsWeight(weight)
22: {}
23:
24: Animal::Animal():
25: itsWeight(0)
26: {}
27:
28:
29: template <class T> // declare the template and the parameter
30: class Array // the class being parameterized
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -