版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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四川凉山州交通城市建设投资集团有限责任公司及所属企业招聘专业技术人员及管理人员16人考试参考题库及答案详解
- 2026年衡水市桃城区事业单位人员招聘考试参考试题及答案详解
- 关于2026年业务拓展计划实施效果的评估函(3篇)
- 2026年淄博市张店区事业单位人员招聘考试模拟试题及答案详解
- 2026福建厦门市集美区珩山实验幼儿园非在编教职工招聘4人笔试备考试题及答案详解
- 2026陕西陕富面业有限责任公司招聘(21人)考试参考题库及答案详解
- 2026年库存管理系统升级安排通知函7篇
- 传统节日文化体验:弘扬中华美德小学主题班会课件
- 尊敬师长传承中华民族美德小学主题班会课件
- 湖北省恩施州利川市2027届数学八年级第一学期期末统考模拟试题含解析
- DBJ-T13-204-2021 福建省城市地下管线探测及信息化技术规程
- 部编版八年级上册历史期末考点默写(填空+答案)
- 四年级数学等量关系式的练习题
- MOOC 国际商务-暨南大学 中国大学慕课答案
- 2024年职称英语等级考试综合类(A级)试题及答案
- 2023年嘉兴市招聘警务辅助人员考试真题及答案
- 人教版小学生必背古诗词(129首完整版)
- CCMD3中国精神障碍分类与诊断标准第3版
- 铁总-2014-11-2(铁路建设项目质量安全事故与招标投标挂钩办法铁总建设(2014)-290号)
- 钢结构工程施工工法
- YS/T 320-2014锌精矿
评论
0/150
提交评论