版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
ObjectivesTounderstandthepurposeofgenericprogrammingToknowthemechanismoftemplatesTobeabletodefinefunctiontemplatesandinstantiatefunctiontemplatesTobeabletodefineclasstemplatesandinstantiateclasstemplates01IntroductiontoTemplates04ClassTemplates02FunctionTemplates03FunctionTemplateInstantiation05ClassTemplateInstantiation01IntroductiontoTemplatesWhatisaTemplate?Imaginethatwewanttowriteafunctiontofindthemaximumoneoftwovalues.Inpractice,we’dwanttodefineseveralsuchfunctions,eachofwhichwillfindthemaximumvalueofagiventype.CasestudyintmaxV(int
x,int
y){return(x>y)?x:y;}charmaxV(char
x,char
y){return(x>y)?x:y;}doublemaxV(double
x,double
y){return(x>y)?x:y;}#definemaxV(x,
y)((x>y)?x:y)Problem:Macropresentsthepossibilityforserioussideeffects:notypechecking,repetitiveoperationsandsoon.intmain(){inti=5,j=3;cout<<maxV(++i,j);return0;}Result:7TmaxV(Tx,Ty){return(x>y)?x:y;}Result:6TheConceptofTemplatesTemplatemechanismallowsatypetobeaparameterinthedefinitionofaclassorafunction.TmaxV(Tx,Ty){return(x>y)?x:y;}Templatesprovideasimplewaytorepresentawiderangeofgenericconceptsandsimplewaystocombinethem.Templatesarethefoundationforgenericprogramming.Atemplateisablueprintorformulaforcreatingclassesorfunctions.
TemplatesareoneofC++’scapabilitiesforsoftwarereusability.02FunctionTemplatesFunctionTemplatestemplate<typenameidentifier>,ortemplate<classidentifier>function_declaration(orfunction_definition);template<classT>TmaxV(Tx,Ty){return(x>y)?x:y;}Keywordtemplate<typenameT>TmaxV(Tx,Ty){return(x>y)?x:y;}typeidentifierintmaxV(int
x,int
y){return(x>y)?x:y;}charmaxV(char
x,char
y){return(x>y)?x:y;}doublemaxV(double
x,double
y){return(x>y)?x:y;}templateparameterlistkeywordCasestudySyntaxtodefineafunctiontemplateFunctionTemplatesAfunctiontemplatedefinesafamilyoffunctionsthatcanoperatewith
generictypes.Thisallowsustocreateafunctiontemplatewhosefunctionalitycanbeadaptedtomorethanonetypewithoutrepeatingtheentirecodeforeachtype.03FunctionTemplateInstantiationFunctionTemplatesInstantiationtemplate<typename
T>TmaxV(Tx,Ty);//declarationintmain(){cout<<maxV(3,4)<<endl;cout<<maxV(3.4,67.8)<<endl;cout<<maxV('s','x')<<endl;return0;}template<typename
T>//definitionTmaxV(T
x,T
y){return(x>y)?x:y;}Functiontemplateinstantiationfunction_name<type>(arguments);cout<<maxV<int>(3,4);cout<<maxV<double>(3.4,67.8);cout<<maxV<char>('s','x')Functiontemplateinstantiationisacreationof
aconcretefunction.FunctionTemplatesInstantiationWhenwecallafunctiontemplate,thecompiler(ordinarily)usestheargumentsofthecalltodeducethetemplateparameter(s)(T)forus.cout<<maxV(3,4)<<endl;cout<<maxV(3.4,67.8)<<endl;cout<<maxV('s','x')<<endl;Nocodeisgeneratedfromasourcefilethatcontainsonlytemplatedefinitions.Inorderforanycodetoappear,atemplatemustbeinstantiated:thetemplateargumentsmustbedeterminedsothatthecompilercangenerateanactualfunction.FunctionTemplateswithdifferentTypeParameterstemplate<typename
T1,typename
T2>T1getMin(T1
x,T2
y){return
x<y?x:(T1)y;}intmain(){inti=9,j=6;doublea=8.3,b=7.8;cout<<getMin(i,a);return0;}cout<<getMin<int,double>(i,a);template<typename
T1,T2>//errorT1getMin(T1
x,T2
y){return
x<y?x:(T1)y;}FunctionTemplatesandOverloadingBothoftheymakecodesmorecompactandconvenient.Functionoverloadingisnormallyusedtoperformsimilaroridenticaloperationsondifferenttypesofdata.Functiontemplates
areusedtoperformidenticaloperationsondifferenttypesofdata.FunctionTemplates
Overloadingtemplate<typename
T>voidSwap(T&x,T&y);voidSwap(int&x,int&y);intmain(){inti=9,j=6;doublea=8.3,b=7.8;chars='4',t='5';Swap(i,j);Swap(a,b);Swap(s,t);return0;}template<typename
T>voidSwap(T&x,T&y){Ttemp;temp=x;x=y;y=temp;cout<<"Calloftemplate\n";}voidSwap(int&x,int&y){inttemp;temp=x;x=y;y=x;cout<<"Calloffunction\n";}Result:CalloffunctionCalloftemplateCalloftemplateWhenanon-templatefunctionprovidesanequallygoodmatchforacallasafunctiontemplate,thenon-templateversionispreferred.FunctionTemplates
OverloadingTemplate<typenameT>TgetMin(Tp1,Tp2);TgetMin(Tp1,Tp2,Tp3);Template<typenameT>TgetMin(Tp1,Tp2);intgetMin(intp1,intp2);Wecandeclareseveralfunctiontemplateswiththesamenameandevendeclareacombinationoffunctiontemplatesandordinaryfunctionswiththesamename.Thecompileralwaysmatchesfirstfunctionprototypes(exactlymatching),andthenfunctiontemplates.FunctionTemplates
Overloadingtemplate<typenameT>TgetMax(Tx,Ty){cout<<"callingtemplate\n";return(x>y)?x:y;}intgetMax(inti,intj){cout<<"callingafunctionwithinttype\n";return(i>j)?i:j;}intgetMax(doubled,inti){cout<<"callingafunctionwithadoubletype\n";return(d>i)?(int)d:i;}constintn=7;intmain(){inti=5,j=6;doublea=8.3,b=7.8;charc1='a',c2='b';cout<<getMax(i,j)<<endl;cout<<getMax(c1,c2)<<endl;cout<<getMax(a,b)<<endl;cout<<getMax(n,i)<<endl;cout<<getMax('a',1)<<endl;cout<<getMax(2.7,4)<<endl;return0;}123112232FunctionTemplatesResult:callingafunctionwithinttype6callingtemplatebcallingtemplate8.3callingafunctionwithinttype7callingafunctionwithinttype97callingafunctionwithadoubletype404ClassTemplatesClassTemplatesStackisakindofdatastructurewithLIFO(lastin,firstout).Ithastwoprincipaloperations:pushandpop.CasestudyStack+Stack()+~Stack()-IsEmpty():bool-IsFull():bool+push(int&):void+pop():int+peak():int+getSize():intconst-element:int*size:intconst-top:intClassTemplatesclass
Stack{public:Stack();~Stack();voidpush(int&i);intpop();
intpeak();intgetSize()const;private:boolIsEmpty();boolIsFull();const
intsize;int*element;inttop;};Stack+Stack()+~Stack()-IsEmpty():bool-IsFull():bool+push(int&):void+pop():int+peak():int+getSize():intconst-element:int*size:intconst-top:intStack::Stack():size(5),top(0){element=new
int[size];}Stack::~Stack(){delete[]element;}bool
Stack::IsEmpty(){return--top==-1;}bool
Stack::IsFull(){returntop>=size?true:false;}void
Stack::push(int&i){if(!IsFull())element[top++]=i;elsethrow-1;}int
Stack::pop(){if(IsEmpty())throw-2;returnelement[top];}int
Stack::peak(){returnelement[top-1];}int
Stack::getSize()const{returntop;}ClassTemplatesintmain(){Stackst;try{for(inti=0;i<4;i++)st.push(i);cout<<
"----------------\n";cout<<st.getSize()<<st.peak()<<endl;intnum=st.getSize()+1;for(inti=0;i<num;i++)cout<<st.pop()<<
"";}catch(inte){if(e==-1)cout<<
"Thestackisfull.\n";if(e==-2)cout<<
"Thestackisempty.\n";}}template<typename
T>class
Stack{public:Stack();~Stack();voidpush(T&i);Tpop();Tpeak();intgetSize()const;private:boolIsEmpty();boolIsFull();const
intsize;T*element;inttop;};Definitionof
aClassTemplatetemplate<classT>Tisagenerictype(typeparameter)Defineaclassasatemplate.Thisclassiscalledclasstemplate.Typeparameterintheclassmaybedatamembers,andmemberfunctions’parameters,andreturningvalueClassTemplatetemplate<typename
T>Stack<T>::Stack():size(5),top(0){element=new
T[size];}template<typename
T>Stack<T>::~Stack(){delete[]element;}template<typename
T>bool
Stack<T>::IsEmpty(){return--top==-1;}template<typename
T>bool
Stack<T>::IsFull(){returntop<size?true:false;}template<typename
T>void
Stack<T>::push(T&i){if(IsFull())element[top++]=i;elsethrow-1;}template<typename
T>T
Stack<T>::pop(){if(IsEmpty())throw-2;returnelement[top];}template<typename
T>T
Stack<T>::peak(){returnelement[top-1];}template<typename
T>int
Stack<T>::getSize()const{returntop;}05ClassTemplateInstantiationClassTemplateInstantiationintmain(){Stack<int>st;try{for(inti=0;i<4;i++)st.push(i);cout<<
"----------------\n";cout<<st.getSize()<<st.peak()<<endl;intnum=st.getSize()+1;for(inti=0;i<num;i++)cout<<st.pop()<<
"";}catch(inte){if(e==-1)cout<<
"Thestackisfull.\n";if(e==-2)cout<<
"Thestackisempty.\n";}}Classtemplateisinstantiated.st
isatemplateclassobjectTheprocessofgeneratingaconcreteclassfromatemplatedefinitionandtemplateargumentsisoftencalledclass
templateinstantiation.ClassTemplateInstantiationclass
A{public:A()=default;A(int
x):a(x){}friend
ostream&operator<<(ostream&o,A&obj){o<<obj.a;
returno;}private:inta;};intmain(){Stack<A>stObj;try{cout<<
"objectsarepushedintoastackonebyone.\n";for(inti=0;i<4;i++){Aobj=A(i);stObj.push(obj);}Aobj=stObj.peak();cout<<stObj.getSize()<<obj<<endl;cout<<
"objectsarepopedfromastackonebyone.\n";intnum=stObj.getSize()+1;for(inti=0;i<num;i++){Atemp=stObj.pop();cout<<temp;}}catch(inte){if(e==-1)cout<<
"Thestackisfull.\n";if(e==-2)cout<<
"Thestackisempty.\n";}}DefinitionofClassTemplateA<T>-a:T+A(T)+operator+(A<T>&):A<T>&<<C++Global>>+operator<<(ostream&,A<T>&):ostream&+operator>>(istream&,A<T>&):istream&<<C++Friend>>template<typename
T>class
A{public:A(T);A<T>&operator+(A<T>&);friend
ostream&operator<<(ostream&out,A<T>&obj){out<<obj.a<<endl;return
out;}friend
istream&operator>>(istream&in,A<T>&obj){in>>obj.a;return
in;}private:Ta;};ClassTemplateInstantiationtemplate<typename
T>A<T>::A(T
type){a=type;}template<typename
T>A<T>&A<T>::operator+(A<T>&obj){a=a+obj.a;return*this;}intmain(){A<int>intA1(10),intA2(20);cout<<intA1+intA2;cout<<intA2;
A<char>charA(''),charB('');cin>>charA;cin>>charB;cout<<charA+charB;
return0;}Eachinstantiationofaclasstemplateconstitutesanindependentclass.Non-TypeParametersforTemplatestemplate<typename
T,intN>class
mysequence{Tmemblock[N];public:voidsetMember(intx,Tvalue);TgetMember(intx);};template<typename
T,intN>void
mysequence<T,N>::setMem
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度網(wǎng)絡(luò)安全風(fēng)險(xiǎn)評(píng)估與解決方案合同范本3篇
- 二零二五版股權(quán)激勵(lì)合同:某上市公司對(duì)高級(jí)管理人員股權(quán)激勵(lì)計(jì)劃3篇
- 2025年度時(shí)尚服飾店開(kāi)業(yè)活動(dòng)承包合同3篇
- 2025年度高端不銹鋼醫(yī)療器械制造委托合同3篇
- 二零二五版智能穿戴設(shè)備代加工合同范本2篇
- 二零二五年度環(huán)保型車間生產(chǎn)承包服務(wù)合同范本3篇
- 二零二五年高管子女教育援助與扶持合同3篇
- 2025年草場(chǎng)租賃與牧區(qū)基礎(chǔ)設(shè)施建設(shè)合同3篇
- 二零二五版涵洞工程勞務(wù)分包單價(jià)及工期延誤賠償合同3篇
- 二零二五版財(cái)務(wù)報(bào)表編制會(huì)計(jì)勞動(dòng)合同范本3篇
- GB/T 34241-2017卷式聚酰胺復(fù)合反滲透膜元件
- GB/T 12494-1990食品機(jī)械專用白油
- 運(yùn)輸供應(yīng)商年度評(píng)價(jià)表
- 成熙高級(jí)英語(yǔ)聽(tīng)力腳本
- 北京語(yǔ)言大學(xué)保衛(wèi)處管理崗位工作人員招考聘用【共500題附答案解析】模擬試卷
- 肺癌的診治指南課件
- 人教版七年級(jí)下冊(cè)數(shù)學(xué)全冊(cè)完整版課件
- 商場(chǎng)裝修改造施工組織設(shè)計(jì)
- 統(tǒng)編版一年級(jí)語(yǔ)文上冊(cè) 第5單元教材解讀 PPT
- 加減乘除混合運(yùn)算600題直接打印
- ASCO7000系列GROUP5控制盤使用手冊(cè)
評(píng)論
0/150
提交評(píng)論