软件设计课件:Lecture 12 CPP Template

上传人:ni****g 文档编号:570198166 上传时间:2024-08-02 格式:PPT 页数:47 大小:562KB
返回 下载 相关 举报
软件设计课件:Lecture 12 CPP Template_第1页
第1页 / 共47页
软件设计课件:Lecture 12 CPP Template_第2页
第2页 / 共47页
软件设计课件:Lecture 12 CPP Template_第3页
第3页 / 共47页
软件设计课件:Lecture 12 CPP Template_第4页
第4页 / 共47页
软件设计课件:Lecture 12 CPP Template_第5页
第5页 / 共47页
点击查看更多>>
资源描述

《软件设计课件:Lecture 12 CPP Template》由会员分享,可在线阅读,更多相关《软件设计课件:Lecture 12 CPP Template(47页珍藏版)》请在金锄头文库上搜索。

1、Lecture 11. C+ TemplatesSoftware Design II C+ Templates2 / 4702 August 2024OutlineIntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates3 / 4702 August 2024Generic ProgramminglIn the simplest definition, generic programming is a style of computer

2、programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. lThis approach, pioneered by ML in 1973, permits writing common functions or types that differ only in the set of types on which they

3、operate when used, thus reducing duplication. Software Design II C+ Templates4 / 4702 August 2024对不同类型的数组,实现自加算法对不同类型的数组,实现自加算法1. 不使用函数模板不使用函数模板void selfAdd( int array, int val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; void selfAdd( float array, float val, int size ) for ( int i = 0;

4、i size; i+ )arrayi += val ; void selfAdd( double array, double val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; 实现代码相同,支持数据类型不同ExampleSoftware Design II C+ Templates5 / 4702 August 2024对不同类型的数组,实现自加算法对不同类型的数组,实现自加算法2. 使用函数模板使用函数模板Template void selfAdd( T array, T val, int size ) for ( in

5、t i = 0; i size; i+ )arrayi += val ; ExampleSoftware Design II C+ Templates6 / 4702 August 2024Easily create a large range of related functions or classes 将一段程序所处理的对象的数据类型参数化,以使得这段程序可以用于处理多种不同数据类型的对象。这避免了功能相同,数据类型不同的类出现, 实现代码复用。 将一个类所需要的数据类型参数化,使得该类成为能处理多种数据类型的通用类。在类的对象被创建时,通过指定参数所属的数据类型,来将通用类实例化。这里

6、的数据类型包括:1. 数据成员的类型 2. 成员函数的参数的类型 3. 函数返回值的类型TemplatesSoftware Design II C+ Templates7 / 4702 August 2024Easily create a large range of related functions or classes 将一段程序所处理的对象的数据类型参数化,以使得这段程序可以用于处理多种不同数据类型的对象。这避免了功能相同,数据类型不同的类出现, 实现代码复用。在template declarations(模板声明)中对模板类型参数定义时, class 和 typename是相同的。t

7、emplate class Widget; / uses classtemplate class Widget; / uses typenameTemplatesSoftware Design II C+ Templates8 / 4702 August 2024OutlineIntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates9 / 4702 August 2024Function template - the blueprint

8、of the related functions函数模板提供了一类函数的抽象,即代表一类函数。函数模板实例化后生成具体的模板函数。Template function - a specific function made from a function template模板函数是具体的函数。一般来说,模板函数在需要的时候才会生成。如templateT add(T a, T b) 在没有使用此函数模板的时候,并不会实例化任何函数模板,当调用add(1, 2)的时候,会生成模板函数int add(int a, int b),当调用add(1.2, 1.4)的时候,才会生成模板函数double add

9、(double a, doule b)Function Template vs. Template FunctionSoftware Design II C+ Templates10 / 4702 August 2024l类和对象、函数模板和模板函数、类模板和模板类之间的关系。类对象函数模板(一类函数)模板函数(具体的函数)实例化生成实例化生成类模板(类型参数化)模板类(具体的类)实例化生成InstantiationSoftware Design II C+ Templates11 / 4702 August 2024lFunction templates 普通函数普通函数和类的成员函数类的成

10、员函数可以声明为函数模板。lFormat:template returnTypefunctionName(parameterList)/definition Example:Example:Template void selfAdd( T array, T val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; Function templatesSoftware Design II C+ Templates12 / 4702 August 2024l模板函数的参数分为:函数实参函数实参和模板实参模板实参。Template vo

11、id selfAdd( T array, T val, int size ) int main() int a10, val = 2 ;seftAdd( a, val, 10 ) ; /省略模板实参seftAdd( a, val, 10 ) ; return 0 ;模板实参函数实参Function templatesSoftware Design II C+ Templates13 / 4702 August 2024l模板函数的模板实参可以省略,编译器将从函数实参的类型中推断。l下列情况,不能省略。1. 从函数实参获得的信息有矛盾2. 需要获得特定类型的返回值3. 虚拟类型参数没有出现在模板

12、函数的形参表中4. 函数模板含有常规形参Function templatesSoftware Design II C+ Templates14 / 4702 August 20241. 从函数实参获得的信息有矛盾:templateT add(T a,T b)return a+b;而调用语句为:cout add( 3.0, 5 ) endl ; /error:歧义产生cout add( 3.0, 5 ) endl ; /OK!Template parametersSoftware Design II C+ Templates15 / 4702 August 20242. 需要获得特定类型的返回值

13、:templateT add(T a,T b)return a+b;需要add返回一个 int 型的值,直接调用add( a, b ) ;Template parametersSoftware Design II C+ Templates16 / 4702 August 20243. 虚拟类型参数没有出现在模板函数的形参表中(多义性)。如下图所示,为避免T2的数据类型未知,必须指定T2的数据类型。templateT2add(T1a,T3b)returna+b;voidmain()coutshowpoint;coutadd(3,5L)endl;coutadd(3,5L)endl;程序运行结果为:

14、程序运行结果为:88.00000Template parametersSoftware Design II C+ Templates17 / 4702 August 2024l当模板定义含有常规形参时,如果此常规形参并未同时出现在函数模板的函数形参表中,则在调用时,无法通过函数实参,初始化此参数,故而必须显式的给出对应的模板实参。templatesum(Tdata,T&result)result=0;for(inti=0;irows;i+)result+=datai;intmain()intd3=1,2,3;intr;sum(d,r);/此处必须显式给出对应于常规参数的模板实参此处必须显式给出

15、对应于常规参数的模板实参Template parametersSoftware Design II C+ Templates18 / 4702 August 2024Overloading A Function TemplatelWhich version to use?(a) template TYPE max(TYPE x, TYPE y);(c) template TYPE max(TYPE x, int n);(b) template TYPE max(TYPE x, TYPE y, TYPE z); (d) double max(int x, double y); Sequence

16、of matching:(1)The common function with matching parameter list (no type conversion);(2)The matching function template (no type conversion);(3)The common function with matching parameter list after implicit type conversion;(4) Otherwise, compiling error.Example:(4)max(array1, 5);(5)max(2.1, 4.5)(6)m

17、ax(B, 9)Example:(1)max(1, 1.2);(2)max(2, 3);(3)max(3, 4, 5);Software Design II C+ Templates19 / 4702 August 2024OutlineIntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates20 / 4702 August 2024lClass templates Allow type-specific versions of gene

18、ric classeslFormat:template class ClassNameT var;/ other definitions . ; ;Need not use T, any identifier will workTo create an object of the class, typeClassName ClassName myObject;Example: Stack doubleStack;Class templatesSoftware Design II C+ Templates21 / 4702 August 2024lFunction Template in cla

19、ssDefined normally, but preceded by templateGeneric data in class listed as type TBinary scope resolution operator usedMyClass:MyClass(int size)Function template in class definition:/Constructor definition - creates an array of type TtemplateMyClass:MyClass(int size) myArray = new Tsize;Class templa

20、tesSoftware Design II C+ Templates22 / 4702 August 2024l模板形参的名字不能在模板内部重用,也就是说一个名字在一个模板中只能使用一次:template /errorl类模板的声明和构造子定义中模板形参的名字可以不同:声明:template class A. 构造子:template A:A().Template parametersOutlinetstack1.h (Part 1 of 3)Outlinetstack1.h (Part 2 of 3)Outlinetstack1.h (Part 3 of 3)fig22_01.cpp (Pa

21、rt 1 of 3)Outlinefig22_01.cpp (Part 2 of 3)Outlinefig22_01.cpp (Part 3 of 3)Program OutputPushingelementsontodoubleStack1.12.23.34.45.5Stackisfull.Cannotpush6.6PoppingelementsfromdoubleStack5.54.43.32.21.1Stackisempty.CannotpopPushingelementsontointStack12345678910Stackisfull.Cannotpush11Poppingelem

22、entsfromintStack10987654321Stackisempty.CannotpopOutlinefig22_02.cpp (Part 1 of 2)Outlinefig22_02.cpp (Part 2 of 2)OutlineProgram OutputPushingelementsontodoubleStack1.12.23.34.45.5Stackisfull.Cannotpush6.6PoppingelementsfromdoubleStack5.54.43.32.21.1Stackisempty.CannotpopPushingelementsontointStack

23、12345678910Stackisfull.Cannotpush11PoppingelementsfromintStack10987654321Stackisempty.CannotpopSoftware Design II C+ Templates31 / 4702 August 2024lCan use non-type parameters in class templates可以是常整数(包括枚举)、指向外部链接对象的指针,而浮点数,指向内部链接对象的指针则不行。must be constant at compile timeExample:Template Stack mostRe

24、centSalesFigures;Defines object of typeStackTemplate parametersSoftware Design II C+ Templates32 / 4702 August 2024Non-type parameters are resolved at compile time, not runtimeExample: This may appear in the class definition: Template T stackHolder elements ; /array to holdstackThe array is created

25、at compile time, rather than dynamic allocation at execution timeTemplate parametersSoftware Design II C+ Templates33 / 4702 August 2024Template parameterslClass templates can have default arguments for type or value parameters.ltemplate class A;lFunction templates CANNOT have default argumentsSoftw

26、are Design II C+ Templates34 / 4702 August 2024lClasses can be overridden For template class Array, define a class namedArrayThis new class overrides the class template formyCreatedTypeThe template remains for unoverriden typesClass template specializationSoftware Design II C+ Templates35 / 4702 Aug

27、ust 2024l应用场景:即想使用模板,同时又需要对一个特殊类型做不同的实现。/ class template: template class specTemplate T m_var; public: specTemplate (T inData) m_var = inData; T increase () return +m_var; ; / class template specialization: template class specTemplate char m_var; public: specTemplate (char arg) m_var = arg; char upp

28、erCase () if (m_var = a) & (m_var = z) m_var += A-a; return m_var; ;Class templates specializationSoftware Design II C+ Templates36 / 4702 August 2024lA non-template class can be derived from a template class(普通类继承模板类)lA template class can be derived from a non-template class(模板类继承了普通类(非常常见)lA class

29、 template can be derived from a class template(类模板继承类模板)lA template class can be derived from a class template(模板类继承类模板,即继承模板参数给出的基类)Template and inheritanceSoftware Design II C+ Templates37 / 4702 August 20241. 普通类继承模板类templateclassTBaseTdata;classDerived:publicTBase;Template and inheritanceSoftwar

30、e Design II C+ Templates38 / 4702 August 20242. 模板类继承了普通类(非常常见)classBase;templateclassTDerived:publicBaseTdata;Templates and inheritanceSoftware Design II C+ Templates39 / 4702 August 20243. 模板类继承模板类templateclassTBaseTdata1;templateclassTDerived:publicTBaseT2data2;Templates and inheritanceSoftware D

31、esign II C+ Templates40 / 4702 August 20249.4Templates and Inheritance 4. 模板类继承模板参数给出的基类继承哪个基类由模板参数决定#includeusingnamespacestd;classBaseApublic:BaseA()coutBaseAfounedendl;classBaseBpublic:BaseB()coutBaseBfounedendl;templateclassBaseCprivate:Tdata;public:BaseC(Tn):data(n)coutBaseCfouneddataendl;templ

32、ateclassDerived:publicTpublic:Derived():T()coutDerivedfounedendl;voidmain()Derivedx;/BaseA作为基类作为基类Derivedy;/BaseB作为基类作为基类DerivedBaseCz(3);/BaseC作为基类作为基类程序运行结果为:程序运行结果为:BaseAfounedDerivedfounedBaseBfounedDerivedfounedBaseCfouned3DerivedfounedSoftware Design II C+ Templates41 / 4702 August 2024Outline

33、IntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates42 / 4702 August 2024lFriendships allowed between a class template and Global function Member function of another classEntire classlfriend functions, Inside definition of class template X:frien

34、d void f1();f1() a friend of all template classesfriend void f2( X & );f2( X & ) is a friend of X only. The same applies for float, double, etc.friend void A:f3(); Member function f3 of class A is a friend of all template classesfriend void C:f4( X & );C:f4( X & ) is a friend of classX onlyTemplates

35、 and friendsSoftware Design II C+ Templates43 / 4702 August 2024lfriend classes, Inside definition of class template X:friend class Y; Every member function of Y a friend with every template class made from Xfriend class Z;Class Z a friend of class X, etc.Templates and friendsSoftware Design II C+ T

36、emplates44 / 4702 August 2024lNon-template class static data members shared between all objectslTemplate classesEach class (int, float, etc.) has its own copy of static data membersstatic variables initialized at file scopeEach template class gets its own copy of static member functionsTemplates and

37、 static Members Software Design II C+ Templates45 / 4702 August 2024Template is NOT OOlBjarne Stroustrup has described the C+ programming language that he created as la general-purpose programming language that supports procedural programming, data abstraction, object-oriented programming, and gener

38、ic programming. lStrictly speaking, Template is a technique of Generic Programming, NOT of Object-Oriented ProgramminglThe C+ class templates (with inheritance rules) is the application of GP on OOSoftware Design II C+ Templates46 / 4702 August 2024Template vs. other dynamic techniqueslC+ Template vs. PolymorphismCompile time vs. Runtime template is also called a kind of compile time polymorphismlC+ Template vs. MarcoGeneric programming vs. MetaprogrammingTemplate is not the only way of Generic programinge.g. Generic in JavaSoftware Design II C+ Templates47 / 4702 August 2024Thank you!

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号