




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 签定朝鲜停战协议书模板
- 测绘业务分包协议书范本
- 燃气安全合同协议书模板
- 深圳农民房交易协议合同
- 活动承包合同协议书范本
- 汽柴油沥青销售合同范本
- 村委秸秆清运协议书范本
- 稠州银行资金托管协议书
- 第三方委托装修协议合同
- 江苏商标申请代理协议书
- 国家重点研发计划“公共安全风险防控与应急技术装备”2023年立项项目
- YS/T 320-2014锌精矿
- 09S304 卫生设备安装图集
- 酸雾抑制剂化学品安全技术说明书
- 重点监管的危险化学品名录(完整版)
- 解三角形专题 - (解析版)
- 高等教育心理学学习提纲整理
- 桩基施工安全检查表
- 水玻璃有机酯自硬砂工艺简介
- 2022年公司管理制度发布流程
- XXX医院管道护理工作总结
评论
0/150
提交评论