軟件設(shè)計課件:Lecture 12 CPP Template_第1頁
軟件設(shè)計課件:Lecture 12 CPP Template_第2頁
軟件設(shè)計課件:Lecture 12 CPP Template_第3頁
軟件設(shè)計課件:Lecture 12 CPP Template_第4頁
軟件設(shè)計課件:Lecture 12 CPP Template_第5頁
已閱讀5頁,還剩42頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

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

2、 computer 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 w

3、hich they operate when used, thus reducing duplication. Software Design II C+ Templates4 / 47November 30, 2021對不同類型的數(shù)組,實現(xiàn)自加算法對不同類型的數(shù)組,實現(xiàn)自加算法1. 不使用函數(shù)模板不使用函數(shù)模板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

4、( int i = 0; i size; i+ )arrayi += val ; void selfAdd( double array, double val, int size ) for ( int i = 0; i size; i+ )arrayi += val ; 實現(xiàn)代碼相同,支持?jǐn)?shù)據(jù)類型不同ExampleSoftware Design II C+ Templates5 / 47November 30, 2021對不同類型的數(shù)組,實現(xiàn)自加算法對不同類型的數(shù)組,實現(xiàn)自加算法2. 使用函數(shù)模板使用函數(shù)模板Template void selfAdd( T array, T val, int

5、 size ) for ( int i = 0; i size; i+ )arrayi += val ; ExampleSoftware Design II C+ Templates6 / 47November 30, 2021Easily create a large range of related functions or classes將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn), 實現(xiàn)代碼復(fù)用。將一個類所需要的數(shù)據(jù)類型參數(shù)化,使得該類成為能處理多種數(shù)據(jù)類型的通用類。在類的對象被創(chuàng)建時,通過指定參數(shù)所屬

6、的數(shù)據(jù)類型,來將通用類實例化。這里的數(shù)據(jù)類型包括:1. 數(shù)據(jù)成員的類型 2. 成員函數(shù)的參數(shù)的類型 3. 函數(shù)返回值的類型TemplatesSoftware Design II C+ Templates7 / 47November 30, 2021Easily create a large range of related functions or classes將一段程序所處理的對象的數(shù)據(jù)類型參數(shù)化,以使得這段程序可以用于處理多種不同數(shù)據(jù)類型的對象。這避免了功能相同,數(shù)據(jù)類型不同的類出現(xiàn), 實現(xiàn)代碼復(fù)用。在template declarations(模板聲明)中對模板類型參數(shù)定義時, cla

7、ss 和 typename是相同的。template class Widget; / uses classtemplate class Widget; / uses typenameTemplatesSoftware Design II C+ Templates8 / 47November 30, 2021OutlineIntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates9 / 47November 30, 2021Funct

8、ion template - the blueprint of the related functions函數(shù)模板提供了一類函數(shù)的抽象,即代表一類函數(shù)。函數(shù)模板實例化后生成具體的模板函數(shù)。Template function - a specific function made from a function template模板函數(shù)是具體的函數(shù)。一般來說,模板函數(shù)在需要的時候才會生成。如templateT add(T a, T b)在沒有使用此函數(shù)模板的時候,并不會實例化任何函數(shù)模板,當(dāng)調(diào)用add(1, 2)的時候,會生成模板函數(shù)int add(int a, int b),當(dāng)調(diào)用add(1.2

9、, 1.4)的時候,才會生成模板函數(shù)double add(double a, doule b)Function Template vs. Template FunctionSoftware Design II C+ Templates10 / 47November 30, 2021l類和對象、函數(shù)模板和模板函數(shù)、類模板和模板類之間的關(guān)系。類對象函數(shù)模板(一類函數(shù))模板函數(shù)(具體的函數(shù))實例化生成實例化生成類模板(類型參數(shù)化)模板類(具體的類)實例化生成InstantiationSoftware Design II C+ Templates11 / 47November 30, 2021lFun

10、ction templates 普通函數(shù)普通函數(shù)和類的成員函數(shù)類的成員函數(shù)可以聲明為函數(shù)模板。lFormat:template returnType functionName( 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 / 47November 30, 2021

11、l模板函數(shù)的參數(shù)分為:函數(shù)實參函數(shù)實參和模板實參模板實參。Template void selfAdd( T array, T val, int size ) int main() int a10, val = 2 ;seftAdd( a, val, 10 ) ; /省略模板實參seftAdd( a, val, 10 ) ; return 0 ;模板實參函數(shù)實參Function templatesSoftware Design II C+ Templates13 / 47November 30, 2021l模板函數(shù)的模板實參可以省略,編譯器將從函數(shù)實參的類型中推斷。l下列情況,不能省略。1. 從

12、函數(shù)實參獲得的信息有矛盾2. 需要獲得特定類型的返回值3. 虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中4. 函數(shù)模板含有常規(guī)形參Function templatesSoftware Design II C+ Templates14 / 47November 30, 20211. 從函數(shù)實參獲得的信息有矛盾:templateT add(T a,T b)return a+b;而調(diào)用語句為:cout add( 3.0, 5 ) endl ; /error:歧義產(chǎn)生cout add( 3.0, 5 ) endl ; /OK!Template parametersSoftware Design II C+

13、 Templates15 / 47November 30, 20212. 需要獲得特定類型的返回值:templateT add(T a,T b)return a+b;需要add返回一個 int 型的值,直接調(diào)用add( a, b ) ;Template parametersSoftware Design II C+ Templates16 / 47November 30, 20213. 虛擬類型參數(shù)沒有出現(xiàn)在模板函數(shù)的形參表中(多義性)。如下圖所示,為避免T2的數(shù)據(jù)類型未知,必須指定T2的數(shù)據(jù)類型。templateT2 add(T1 a,T3 b)return a+b;void main()

14、coutshowpoint;coutadd(3,5L)endl;coutadd(3,5L)endl;程序運行結(jié)果為:程序運行結(jié)果為:88.00000Template parametersSoftware Design II C+ Templates17 / 47November 30, 2021l當(dāng)模板定義含有常規(guī)形參時,如果此常規(guī)形參并未同時出現(xiàn)在函數(shù)模板的函數(shù)形參表中,則在調(diào)用時,無法通過函數(shù)實參,初始化此參數(shù),故而必須顯式的給出對應(yīng)的模板實參。template sum(T data,T &result)result=0; for(int i=0;irows;i+)result+=

15、datai;int main()int d3=1,2,3;int r; sum(d,r); /此處必須顯式給出對應(yīng)于常規(guī)參數(shù)的模板實參此處必須顯式給出對應(yīng)于常規(guī)參數(shù)的模板實參Template parametersSoftware Design II C+ Templates18 / 47November 30, 2021Overloading A Function TemplatelWhich version to use?(a) template TYPE max(TYPE x, TYPE y);(c) template TYPE max(TYPE x, int n);(b) templat

16、e TYPE max(TYPE x, TYPE y, TYPE z); (d) double max(int x, double y); Sequence 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

17、;(4) Otherwise, compiling error.Example:(4)max(array1, 5);(5)max(2.1, 4.5)(6)max(B, 9)Example:(1)max(1, 1.2);(2)max(2, 3);(3)max(3, 4, 5);Software Design II C+ Templates19 / 47November 30, 2021OutlineIntroductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C

18、+ Templates20 / 47November 30, 2021lClass templates Allow type-specific versions of generic 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;Clas

19、s templatesSoftware Design II C+ Templates21 / 47November 30, 2021lFunction Template in classDefined 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 - c

20、reates an array of type TtemplateMyClass:MyClass(int size) myArray = new Tsize;Class templatesSoftware Design II C+ Templates22 / 47November 30, 2021l模板形參的名字不能在模板內(nèi)部重用,也就是說一個名字在一個模板中只能使用一次:template /errorl類模板的聲明和構(gòu)造子定義中模板形參的名字可以不同:聲明:template class A. 構(gòu)造子:template A:A().Template parametersOutlinetstac

21、k1.h (Part 1 of 3)Outlinetstack1.h (Part 2 of 3)Outlinetstack1.h (Part 3 of 3)fig22_01.cpp (Part 1 of 3)Outlinefig22_01.cpp (Part 2 of 3)Outlinefig22_01.cpp (Part 3 of 3)Program OutputPushing elements onto doubleStack1.1 2.2 3.3 4.4 5.5Stack is full. Cannot push 6.6 Popping elements from doubleStack

22、5.5 4.4 3.3 2.2 1.1Stack is empty. Cannot pop Pushing elements onto intStack1 2 3 4 5 6 7 8 9 10Stack is full. Cannot push 11 Popping elements from intStack10 9 8 7 6 5 4 3 2 1Stack is empty. Cannot popOutlinefig22_02.cpp (Part 1 of 2)Outlinefig22_02.cpp (Part 2 of 2)OutlineProgram OutputPushing ele

23、ments onto doubleStack1.1 2.2 3.3 4.4 5.5Stack is full. Cannot push 6.6 Popping elements from doubleStack5.5 4.4 3.3 2.2 1.1Stack is empty. Cannot pop Pushing elements onto intStack1 2 3 4 5 6 7 8 9 10Stack is full. Cannot push 11 Popping elements from intStack10 9 8 7 6 5 4 3 2 1Stack is empty. Can

24、not pop Software Design II C+ Templates31 / 47November 30, 2021lCan use non-type parameters in class templates可以是常整數(shù)(包括枚舉)、指向外部鏈接對象的指針,而浮點數(shù),指向內(nèi)部鏈接對象的指針則不行。must be constant at compile timeExample:Template Stack mostRecentSalesFigures; Defines object of type StackTemplate parametersSoftware Design II

25、C+ Templates32 / 47November 30, 2021Non-type parameters are resolved at compile time, not runtimeExample: This may appear in the class definition: Template T stackHolder elements ; /array to hold stackThe array is created at compile time, rather than dynamic allocation at execution timeTemplate para

26、metersSoftware Design II C+ Templates33 / 47November 30, 2021Template parameterslClass templates can have default arguments for type or value parameters.ltemplate class A;lFunction templates CANNOT have default argumentsSoftware Design II C+ Templates34 / 47November 30, 2021lClasses can be overridde

27、n For template class Array, define a class namedArrayThis new class overrides the class template for myCreatedTypeThe template remains for unoverriden typesClass template specializationSoftware Design II C+ Templates35 / 47November 30, 2021l應(yīng)用場景:即想使用模板,同時又需要對一個特殊類型做不同的實現(xiàn)。/ class template: template c

28、lass 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 upperCase () if (m_var = a) & (m_var = z) m_var += A-a; return m_va

29、r; ;Class templates specializationSoftware Design II C+ Templates36 / 47November 30, 2021lA non-template class can be derived from a template class(普通類繼承模板類)lA template class can be derived from a non-template class(模板類繼承了普通類(非常常見)lA class template can be derived from a class template(類模板繼承類模板)lA te

30、mplate class can be derived from a class template(模板類繼承類模板,即繼承模板參數(shù)給出的基類)Template and inheritanceSoftware Design II C+ Templates37 / 47November 30, 20211. 普通類繼承模板類templateclass TBaseT data;class Derived:public TBase;Template and inheritanceSoftware Design II C+ Templates38 / 47November 30, 20212. 模板類

31、繼承了普通類(非常常見)class Base;templateclass TDerived:public BaseT data;Templates and inheritanceSoftware Design II C+ Templates39 / 47November 30, 20213. 模板類繼承模板類templateclass TBaseT data1;templateclass TDerived:public TBaseT2 data2;Templates and inheritanceSoftware Design II C+ Templates40 / 47November 30

32、, 20219.4Templates and Inheritance 4. 模板類繼承模板參數(shù)給出的基類繼承哪個基類由模板參數(shù)決定#includeusing namespace std;class BaseApublic:BaseA()coutBaseA founedendl;class BaseBpublic:BaseB()coutBaseB founedendl;templateclass BaseCprivate:T data;public:BaseC(T n):data(n)coutBaseC founed dataendl;templateclass Derived:public T

33、public:Derived():T()coutDerived founedendl;void main()Derived x;/ BaseA作為基類作為基類Derived y;/ BaseB作為基類作為基類DerivedBaseC z(3); / BaseC作為基類作為基類程序運行結(jié)果為:程序運行結(jié)果為:BaseA founedDerived founedBaseB founedDerived founedBaseC founed 3Derived founedSoftware Design II C+ Templates41 / 47November 30, 2021OutlineIntr

34、oductionFunction templatesClass templatesTemplates with friends & staticSoftware Design II C+ Templates42 / 47November 30, 2021lFriendships allowed between a class template and Global function Member function of another classEntire classlfriend functions, Inside definition of class template X:fr

35、iend 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

36、class X onlyTemplates and friendsSoftware Design II C+ Templates43 / 47November 30, 2021lfriend 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+ Tem

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論