Tải bản đầy đủ - 0 (trang)
Chapter 16.  Templates and Generic Programming

Chapter 16.  Templates and Generic Programming

Tải bản đầy đủ - 0trang

ofvectorsthatdifferbytheelementtypethatthevector

contains.

Templatesarethefoundationofgenericprogramming.Wecan,

andhave,usedtemplateswithoutunderstandinghowtheyare

defined.Inthischapterwe'llseehowwecandefineourown

templateclassesandfunctions.

Genericprogramming,likeobject-orientedprogramming,relies

onaformofpolymorphism.ThepolymorphisminOOPapplies

atruntimetoclassesrelatedbyinheritance.Wecanwritecode

thatusessuchclassesinwaysthatignorethetypedifferences

amongthebaseandderivedclasses.Aslongasweuse

referencesorpointerstothebasetype,wecanusethesame

codeonobjectsofthebasetypeoratypederivedfromthat

type.

Genericprogrammingletsuswriteclassesandfunctionsthat

arepolymorphicacrossunrelatedtypesatcompiletime.A

singleclassorfunctioncanbeusedtomanipulateobjectsofa

varietyoftypes.Thestandardlibrarycontainers,iterators,and

algorithmsaregoodexamplesofgenericprogramming.The

librarydefineseachofthecontainers,iterators,andalgorithms

inatype-independentmanner.Wecanuselibraryclassesand

functionsonmostanykindoftype.Forexample,wecandefine

avectorofSales_itemobjectseventhoughthedesignersofvector

couldhavehadnoknowledgeofourapplication-specificclass.

InC++,templatesarethefoundationforgenericprogramming.

Atemplateisablueprintorformulaforcreatingaclassora

function.Forexample,thestandardlibrarydefinesasingle

classtemplatethatdefineswhatitmeanstobeavector.That

templateisusedtogenerateanynumberoftype-specificvector

classesforexample,vectororvector.PartIIshowed

howtousegenerictypesandfunctions;thischaptershowshow

wecandefineourowntemplates.



16.1.TemplateDefinitions

Let'simaginethatwewanttowriteafunctiontocomparetwo

valuesandindicatewhetherthefirstislessthan,equalto,or

greaterthanthesecond.Inpractice,we'dwanttodefine

severalsuchfunctions,eachofwhichcouldcomparevaluesofa

giventype.Ourfirstattemptmightbetodefineseveral

overloadedfunctions:

//returns0ifthevaluesareequal,-1ifv1issmaller,1ifv2

intcompare(conststring&v1,conststring&v2)

{

if(v1
if(v2
return0;

}

intcompare(constdouble&v1,constdouble&v2)

{

if(v1
if(v2
return0;

}



Thesefunctionsarenearlyidentical:Theonlydifference

betweenthemisthetypeoftheirparameters.Thefunction

bodyisthesameineachfunction.

Havingtorepeatthebodyofthefunctionforeachtypethatwe

compareistediousanderror-prone.Moreimportantly,weneed

toknowinadvanceallthetypesthatwemighteverwantto

compare.Thisstrategycannotworkifwewanttobeabletouse

thefunctionontypesthatwedon'tknowabout.



16.1.1.DefiningaFunctionTemplate

Ratherthandefininganewfunctionforeachtype,wecan

defineasinglefunctiontemplate.Afunctiontemplateisa

type-independentfunctionthatisusedasaformulafor

generatingatype-specificversionofthefunction.Forexample,

wemightwriteafunctiontemplatenamedcompare,whichwould

tellthecompilerhowtogeneratespecificversionsofcomparefor

thetypesthatwewanttocompare.

Thefollowingisatemplateversionofcompare:

//implementstrcmp-likegenericcomparefunction

//returns0ifthevaluesareequal,1ifv1islarger,-1ifv1issmaller

template

intcompare(constT&v1,constT&v2)

{

if(v1
if(v2
return0;

}



Atemplatedefinitionstartswiththekeywordtemplatefollowed

byatemplateparameterlist,whichisacomma-separated

listofoneormoretemplateparametersbracketedbythe

less-than(<)andgreater-than(>)tokens.

Thetemplateparameterlistcannotbeempty.



TemplateParameterList

Thetemplateparameterlistactsmuchlikeafunction

parameterlist.Afunctionparameterlistdefineslocal

variable(s)ofaspecifiedtypebutleavesthosevariables

uninitialized.Atruntime,argumentsaresuppliedthatinitialize

theparameters.

Analogously,templateparametersrepresenttypesorvalueswe

canuseinthedefinitionofaclassorfunction.Forexample,our

comparefunctiondeclaresonetypeparameternamedT.Inside

compare,wecanusethenameTtorefertoatype.Whichactual

typeTrepresentsisdeterminedbythecompilerbasedonhow

thefunctionisused.

Atemplateparametercanbeatypeparameter,which

representsatype,oranontypeparameter,whichrepresents

aconstantexpression.Anontypeparameterisdeclared

followingatypespecifier.We'llseemoreaboutnontype

parametersinSection16.1.5(p.632).Atypeparameteris

definedfollowingthekeywordclassortypename.Forexample,

classTisatypeparameternamedT.Thereisnodifference

betweenclassandtypenameinthiscontext.



UsingaFunctionTemplate

Whenweuseafunctiontemplate,thecompilerinferswhat

templateargument(s)tobindtothetemplateparameter(s).

Oncethecompilerdeterminestheactualtemplateargument(s),

itinstantiatesaninstanceofthefunctiontemplateforus.

Essentially,thecompilerfiguresoutwhattypetouseinplaceof

eachtypeparameterandwhatvaluetouseinplaceofeach

nontypeparameter.Havingdeducedtheactualtemplate

arguments,itgeneratesandcompilesaversionofthefunction

usingthoseargumentsinplaceofthecorrespondingtemplate



parameters.Thecompilertakesonthetediumof(re)writingthe

functionforeachtypeweuse.

Giventhecalls



intmain()

{

//Tisint;

//compilerinstantiatesintcompare(constint&,constint&)

cout<
//Tisstring;

//compilerinstantiatesintcompare(conststring&,conststr

strings1="hi",s2="world";

cout<
return0;

}



thecompilerwillinstantiatetwodifferentversionsofcompare.

ThecompilerwillcreateoneversionthatreplacesTbyintanda

secondversionthatusesstringinplaceofT.



inlineFunctionTemplates

Afunctiontemplatecanbedeclaredinlineinthesamewayasa

nontemplatefunction.Thespecifierisplacedfollowingthe

templateparameterlistandbeforethereturntype.Itisnot

placedinfrontofthetemplatekeyword.

//ok:inlinespecifierfollowstemplateparameterlist

templateinlineTmin(constT&,constT&);

//error:incorrectplacementofinlinespecifier

inlinetemplateTmin(constT&,constT&);



ExercisesSection16.1.1

Writeatemplatethatreturnstheabsolutevalueofits

parameter.Callthetemplateonvaluesofatleastthreedifferent

Exercise

types.Note:untilwediscusshowthecompilerhandlestemplate

16.1:

instantiationinSection16.3(p.643),youshouldputeach

templatedefinitionandallusesofthattemplateinthesamefile.



Writeafunctiontemplatethattakesareferencetoanostream

Exercise andavalue,andwritesthevaluetothestream.Callthe

16.2: functiononatleastfourdifferenttypes.Testyourprogramby

writingtocout,toafile,andtoastringstream.



Whenwecalledcompareontwostrings,wepassedtwostring

objects,whichweinitializedfromstringliterals.Whatwould

Exercise happenifwewrote:

16.3:

compare("hi","world");



16.1.2.DefiningaClassTemplate

Justaswecandefinefunctiontemplates,wecanalsodefine

classtemplates.

Toillustrateclasstemplates,we'llimplementourown

versionofthestandardlibraryqueue(Section9.7,p.348)

class.Userprogramsoughttousethestandardqueue

class,nottheonewedefinehere.



OurQueuemustbeabletoholdobjectsofdifferenttypes,so

we'lldefineitasaclasstemplate.TheoperationsourQueuewill

supportareasubsetoftheinterfaceofthestandardqueue:

pushtoaddanitemtothebackofthequeue

poptoremovetheitemattheheadofthequeue

fronttoreturnareferencetotheelementattheheadofthe



queue

emptytoindicatewhetherthereareanyelementsinthe



queue

We'lllookathowwemightimplementourQueueinSection16.4

(p.647),butwecanstartbydefiningitsinterface:

templateclassQueue{

public:

Queue();//defaultconstructor

Type&front();//returnelementfromheadof

constType&front()const;

voidpush(constType&);//addelementtobackofQueue

voidpop();//removeelementfromheadof

boolempty()const;//trueifnoelementsinthe

private:

//...

};



Aclasstemplateisatemplate,soitmustbeginwiththe

keywordtemplatefollowedbyatemplateparameterlist.Our

Queuetemplatetakesasingletemplatetypeparameternamed



Type.



Withtheexceptionofthetemplateparameterlist,thedefinition

ofaclasstemplatelookslikeanyotherclass.Aclasstemplate

maydefinedata,function,andtypemembers;itmayuse

accesslabelstocontrolaccesstothosemembers;itdefines

constructorsanddestructors;andsoon.Inthedefinitionofthe

classanditsmembers,wecanusethetemplateparametersas

stand-insfortypesorvaluesthatwillbesuppliedwhenthe

classisused.

Forexample,ourQueuetemplatehasonetemplatetype

parameter.Wecanusethatparameteranywhereatypename

canbeused.Inthistemplatedefinition,weuseTypetoname

thereturntypefromtheoverloadedfrontoperationsandasthe

parametertypeforthepushoperation.



UsingaClassTemplate

Incontrasttocallingafunctiontemplate,whenweuseaclass

template,wemustexplicitlyspecifyargumentsforthetemplate

parameters:

Queueqi;//Queuethatholdsint

Queue>qc;//Queuethatholdsvectors

Queueqs;//Queuethatholdsstring



Thecompilerusestheargumentstoinstantiateatype-specific

versionoftheclass.Essentially,thecompilerrewritesourQueue

classreplacingTypebythespecifiedactualtypeprovidedbythe

user.Inthiscase,thecompilerwillinstantiatethreeclasses:a

versionofQueuewithTypereplacedbyint,asecondQueueclass

thatusesvectorinplaceofType,andathirdthatreplaces

Typebystring.



ExercisesSection16.1.2

Exercise

Whatisafunctiontemplate?Whatisaclasstemplate?

16.4:

Exercise

Defineafunctiontemplatetoreturnthelargeroftwovalues.

16.5:

Exercise Similartoourasimplifiedversionofqueue,writeaclasstemplate

16.6: namedListthatisasimplifiedversionofthestandardlistclass.



16.1.3.TemplateParameters

Aswithafunctionparameter,thenamechosenbythe

programmerforatemplateparameterhasnointrinsicmeaning.

Inourexample,wenamedcompare'stemplatetypeparameterT,

butwecouldhavenameditanything:

//equivalenttemplatedefinition

template

intcompare(constGlorp&v1,constGlorp&v2)

{

if(v1
if(v2
return0;

}



Thiscodedefinesthesamecomparetemplateasbefore.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 16.  Templates and Generic Programming

Tải bản đầy đủ ngay(0 tr)

×