




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年工业运动控制系统合作协议书
- 2025年植物稳态营养肥料项目发展计划
- 从心灵出发走进学生世界的教育方法探索
- 2025年高温电磁阀项目发展计划
- 个性化教学的重要一环基于大数据的未来教育技术分析
- 教育国际化与政策变革解读
- 教育心理学的未来发展提升学习成效的路径
- 教育建筑的绿色改造与可持续发展目标
- 教育政策的跨文化解读与影响分析
- 医学教育与商业科技的结合开启新篇章
- 盾构隧道用管片招标采购
- 《环境与资源保护法(第5版)》全套教学课件
- 2024年03月北京西城区教委事业单位招考聘用764人笔试近年2018-2023典型考题及考点剖析附答案带详解
- 人教版2024七年级英语上册Starter Unit(1-3)单词精讲课件
- 广东省深圳市宝安区2023-2024学年五年级下学期期末英语试题
- 成品烟道安装施工方案
- 《路遥人生》读书分享课件
- 律师保密协议书
- 小学2024年暑假致家长的一封信9篇
- 2024护士聘用合同模板
- 强力霉素的质量控制与标准制定
评论
0/150
提交评论