版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
12Templates1OutlineFunctiontemplatesClasstemplates2KnowledgePointsWritinggenericfunctions
Book:AcceleratedC++,Chapter83ReferenceMaterialsTemplates
Book:C++HowtoProgram(8thedition),Chapter14(15pages)IntroductionManyoftheideasandexamplespresentedinthelastfewlessonshaveillustratedwaysofmakingcode"generalpurpose".SuchasoverloadingfunctionandinheritanceTheideaofatemplateisthatitdefinesoperationsforanunboundedvarietyofrelateddatatypes.ProgrammingusingtypesasparametersIntroductionKindsoftemplateFunctiontemplatesClasstemplatesTheydescribe,insomegeneralway,howtomanipulatedataelements.Theyworkwithanykindofdatathatsupportstherequiredoperations.TothinkAfunctionmax()takestwodataelementsasarguments,andreturnsthelarger.Wmax(inta,intb){
if(a>b)
returna;
else
returnb;}doublemax(doublea,doubleb){
if(a>b)
returna;
else
returnb;}Boxmax(Boxa,Box
b){
if(a>b)
returna;
else
returnb;}Therehastobeabetterway!template<typenameT>Tmax(constT&a,constT&b){
if(a>b)
returna;
else
returnb;}IndicatesatemplateisbeingdefinedTisaformaltemplatetypeparameterFunctiontemplateDescribesafunctionformatthatwheninstantiatedwithparticularsgeneratesafunctiondefinitionWriteonce,usemultipletimesFunctionTemplatesCodesegmentintInput1=PromptAndRead();intInput2=PromptAndRead();cout<<max(Input1,Input2)<<endl;Causesthefollowingfunctiontobegeneratedfromourtemplateintmax(const
int&a,const
int&b){
if(a>b)
returna;
else
returnb;}TemplateFunctionCodesegmentdoubleValue1=4.30;doubleValue2=19.54;cout<<max(Value1,Value2)<<endl;Causesthefollowingfunctiontobegeneratedfromourtemplatedoublemax(const
double&a,const
double&b){
if(a>b)
returna;
else
returnb;}TemplateFunctionOperator>needstobedefinedfortheactualtemplateparametertype.If>isnotdefined,thenacompile-timeerroroccursCodesegmentBoxb1(6,4,7);Boxb2(5,5,8);cout<<max(b1,b2)<<endl;CausesthefollowingfunctiontobegeneratedfromourtemplateBoxmax(constBox&a,constBox&b)
{
if(a>b)
returna;
else
returnb;}TemplateFunctionNotemplatefunction,justacompile-timeerror
Thetemplateparametersmustbeexactmachwheninstantiatingafunctiontemplate.CodesegmentBoxb1(6,4,7);doubled=2.0;cout<<max(b1,d)<<endl;Whatfunctionwillbegeneratedfromourtemplate???TemplateFunctiontemplate<typenameT>TMin(constT&a,constT&b){
if(a<b)
returna;
else
returnb;}intMin(const
int&a,const
int&b){
if(a<b)
returna;
else
returnb;}intmain(){
inta=1,b=2;cout<<Min(a,b)<<endl;
return0;}Forfollowingcodesegment,whatishappened?Compilermatchoverloadingfunctionfirst,andthenmatchtemplatefunctionFunctionTemplatesAdviceboolfind(intval);boolfind(constMatrix&val);template<typenameelemType>boolfind(elemType&val);
Indefinitionoftemplate,theparametersoffunctioncommonlyusereference.ClassTemplatedeclarationtemplate<template_arguments_list>classclass_name{//definitionoftemplate};template<template_arguments_list>return_typeclass_name<template_argument_names_list>::member_function_name(member_function_argument_list){ //body_of_member_function}template<typenameT,intn>classTC{public:TC();
voidAssign(Tsrc);
//...private:TValueArray[n];}ThevaluetemplateparameterThetypetemplateparameterClassTemplatesTC<char,80>A;TC<int,125>B;classTC{public:TC();
voidAssign(charsrc);
//...private:
charValueArray[80];};TCA;classTC{public:TC();
voidAssign(intsrc);
//...private:
intValueArray[125];};TCB;ClassTemplatesExample:generaldatastoringclasstemplate<typenameT>classStore //Classtemplate:implementstoringanytypedata{private: Titem; //tostoredata boolhaveValue; //tomarkwhetherthedataisexistedpublic: Store(void); //defaultconstructor TgetElem(void); //togetthedata voidputElem(Tx); //tostorethedata};//implementationofthedefaultconstructortemplate<typenameT>Store<T>::Store(void):haveValue(0){}template<typenameT>//implementationofthegetElem()TStore<T>::getElem(void){ if(!haveValue) //ifnodatainstore,exittheprogram {cout<<"Noitempresent!"<<endl;exit(1); } returnitem;//returnthestoreddata}template<typenameT>//implementationoftheputElem()voidStore<T>::putElem(Tx){ haveValue=true; item=x;}structStudent{ intid;//学号
floatgpa;//平均分};intmain(){ Studentg={1000,23}; Store<int>s1,s2; Store<Student>s3; s1.putElem(3); s2.putElem(-7); cout<<s1.ge
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026江西九江瑞昌市国投建设工程集团有限公司招聘变更2人笔试参考题库及答案解析
- 2026年宜居城市的建设理念与实践
- 2025年学校食堂报账员笔试及答案
- 2025年太平洋寿险管培笔试及答案
- 2025年邮政公司社招线上笔试及答案
- 2025年湖北初中历史教招笔试及答案
- 2026年计算流体动力学简介
- 2025年兴义特岗免笔试及答案
- 2025年大学记者社文学部笔试及答案
- 2025年阿克苏市人事考试及答案
- 免责协议告知函
- 食物与情绪-营养对心理健康的影响
- 2023气管插管意外拔管的不良事件分析及改进措施
- 麻醉药品、精神药品月检查记录
- 基础化学(本科)PPT完整全套教学课件
- 蕉岭县幅地质图说明书
- 电梯控制系统论文
- (完整word版)人教版初中语文必背古诗词(完整版)
- 湖北省地质勘查坑探工程设计编写要求
- GB/T 4310-2016钒
- GB/T 28799.3-2020冷热水用耐热聚乙烯(PE-RT)管道系统第3部分:管件
评论
0/150
提交评论