Download presentation
Presentation is loading. Please wait.
Published byHilary Osborne Modified over 8 years ago
1
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green
2
Templates ©Bruce M. Reynolds & Cliff Green2 Object orientation Genericity –Genericity is the construction of a class so that one or more of the data types it uses internally is supplied only at compile-time. –While not necessary to implement container classes (set, array, stack, queue), it allows containers to enforce type safety.
3
Templates ©Bruce M. Reynolds & Cliff Green3 Rationale C approach to source code reuse for containers –copy source code, and make changes by hand, or –use void pointers, cast to specific type (either data type or function pointer) Smalltalk approach to source code reuse for containers –Smalltalk defines only a single “object”-based hierarchy –Smalltalk supports only single inheritance –every object in smalltalk is derived from base class “object”, or derived from a class derived from “object” –containers holds items of the generic base class “object”
4
Templates ©Bruce M. Reynolds & Cliff Green4 Rationale Macros - original C++ approach to source code reuse for containers –Stroustrup proposed preprocessor macros for containers –container classes were created as large preprocessor macros for parameterized types –complex, unwieldy, and never caught on
5
Templates ©Bruce M. Reynolds & Cliff Green5 Rationale Multiple inheritance - another C++ approach to generalization and source code reuse for containers –C++allows many, unrelated hierarchies of objects –all C++ objects do not share a common base class –C++ added multiple inheritance so that container classes could be implemented with “object”-based hierarchies Multiple inheritance turned out to be too complex and error- prone – inheritance is the tightest form of coupling
6
Templates ©Bruce M. Reynolds & Cliff Green6 Rationale Templates - current C++ approach to source code reuse for containers, as well as many generalization / specialization approaches –a template reuses source code –container no longer holds a generic base class called “object” –container holds an unspecified parameter –similar to macros (much more powerful, however), but implemented in the compiler itself, not in the preprocessor When the template is used, the parameter is substituted by the compiler
7
Templates ©Bruce M. Reynolds & Cliff Green7 Kinds of templates Function –function templates permit the development of generic algorithms sort min, max Class –class templates permit the development of generic abstract data types (such as containers) tree, set, vector, array, dictionary graph, list, stack, queue
8
Templates ©Bruce M. Reynolds & Cliff Green8 General syntax template normal declaration or definition –where template is a C++ keyword T 0, T 1,…T n are one or more formal type parameters a formal type parameter must be written as “class T” (except for non-type template parameters, covered in a later slide) –keyword “class” means any built-in type or user-defined type
9
Templates ©Bruce M. Reynolds & Cliff Green9 General syntax Type parameters –can be built-in types (int, float, char* ) –can be user-defined types Default values –Type parameters can have default types. –Non-type parameters can have default values. Non-type parameters –OK in class templates –Not OK in function templates –OK in the function definition
10
Templates ©Bruce M. Reynolds & Cliff Green10 General syntax Put all declarations and definitions for a template in a header file (until export is supported) –anything preceded by template<> means the compiler won’t allocate storage at that point –storage is allocated when the template is instantiated –compiler and/or linker remove multiple definitions of an identical template
11
Templates ©Bruce M. Reynolds & Cliff Green11 Function templates Overloaded functions are normally used to perform similar operations on different types of data Function templates are used to perform identical operations on different types of data
12
Templates ©Bruce M. Reynolds & Cliff Green12 Function templates template T min ( T var1, T var2 ); –the function “min” –has two arguments var1 and var2, both of type T returns a variable of type T template T min ( T *pVar1, T *pVar2 ) –the function “min” –has two arguments pVar1 and pVar2, both of type pointer to T returns a variable of type T
13
Templates ©Bruce M. Reynolds & Cliff Green13 Function templates Template functions can be declared… –inline –static –extern –as members of classes Underlying implementation is similar to function overloading Templates allow the simple definition of a range of overloaded functions.
14
Templates ©Bruce M. Reynolds & Cliff Green14 Function templates - instantiation 1.The formal parameters in the function signature are examined. 2.Each formal parameter involving a type parameter is matched with the type of a corresponding argument in the function call. 3.The compiler tries to find a precise match of function name and argument types. 4.Types need not match exactly -- automatic type conversions may be applied.
15
Templates ©Bruce M. Reynolds & Cliff Green15 Function templates - instantiation - continued 5.The type of the call’s arguments are substituted for the formal parameters throughout the template definition. 6.The compiler creates a complete function based on the matched types. 7.The newly created function is compiled.
16
Templates ©Bruce M. Reynolds & Cliff Green16 Function templates - function call resolution Examine all non-template functions –exact match--->call that version –multiple matches--->compile error Examine all template functions –exact match--->instantiate that version call that version –multiple matches--->compile error Re-examine all non-template functions –apply rules for overloaded functions
17
Templates ©Bruce M. Reynolds & Cliff Green17 Function templates - overloading Can define other function templates with the same function name but different function parameters Can also define other non-template functions with the same function name but different function parameters
18
Templates ©Bruce M. Reynolds & Cliff Green18 Class templates Syntax template class className { … }; –where template is a C++ keyword T 0, T 1,…T n are one or more formal type parameters a formal type parameter must be written as “class T” or “typename T” (certain other non-type constructs are also allowed)
19
Templates ©Bruce M. Reynolds & Cliff Green19 Class templates Definition and declaration –Put both declaration and definition in the header file (or include the definition from the header) The value of a type parameter may be –A built-in type –A user-defined type –A parameterized type (another template)
20
Templates ©Bruce M. Reynolds & Cliff Green20 Class templates Declaring an instance template class className { …. } ; className myInstance1; className myInstance2;
21
Templates ©Bruce M. Reynolds & Cliff Green21 Class templates A member function definition outside the class template –Begins with the same template header as the class –Is instantiated when the compiler first sees a call to it Syntax template returnType className ::functionName( … ) { … }
22
Templates ©Bruce M. Reynolds & Cliff Green22 Class templates Static members –A class template can have static members –Each type has its own copy of static data members Declaration static int myValue; Definition (statics must be defined outside of the class) template int className ::myValue = aValue;
23
Templates ©Bruce M. Reynolds & Cliff Green23 Class templates Forward declarations template class className; “Friend” makes a function or class a friend of every template class instantiated from the class template template class className { friend anOtherClass; … };
24
Templates ©Bruce M. Reynolds & Cliff Green24 Class templates Specialization –A class for a specific type can be provided to override the class template for that type –Use to handle a type not easily included in the definition of a class template
25
Templates ©Bruce M. Reynolds & Cliff Green25 Class templates and non-type parameters It is possible to use a non-type parameter among the template parameters –a non-type parameter can have a default argument –the non-type parameter is treated as const Declaration template class Stack { … }; Instantiation Stack myStack;
26
Templates ©Bruce M. Reynolds & Cliff Green26 Class templates Explicit instantiation –May wish to instantiate a template even though you are not creating an object of that type –Allow exact control of the instantiation Syntax –Function template void sort ( char *[] ); –Class template class className ;
27
Templates ©Bruce M. Reynolds & Cliff Green27 Class templates and inheritance Derivation works the same way as with regular classes –A class template can be derived from a template class. –A class template can be derived from a non-template class. –A class template can be derived from a class template. –A non-template class can be derived from a class template.
28
Templates ©Bruce M. Reynolds & Cliff Green28 Standard template library (STL) Templates, once defined, are easy to use! Source code reuse becomes trivial, even for the novice Avoid reinventing the wheel -- the Standard Template Library provides type-safe implementations of –Many of the most popular data structures as containers –Many dozens of popular algorithms to process the data in those containers STL is tested, debugged, and robust!
29
Templates ©Bruce M. Reynolds & Cliff Green29 Standard template library (STL) Common data structures –string –vector –list –deque –set –multiset –map –multimap –stack –queue rapid insertions/deletions at back rapid insertions/deletions anywhere direct access, rapid access at back/front rapid lookup, no duplicates rapid lookup, duplicates OK 1-to-1 mapping, key-based lookup, no dups 1-to-1 mapping, key-based lookup, dups OK LIFO FIFO
30
Templates ©Bruce M. Reynolds & Cliff Green30 Standard template library (STL) Common member functions –empty –size –swap –operator= –operator< –operator== –begin, end –rbegin, rend –erase,clear true if there are no members number of elements swaps elements of 2 containers assign one container to anther forward iterator first, last element reverse iterator first, last element erase or clear 1 or more elements
31
Templates ©Bruce M. Reynolds & Cliff Green31 Standard template library (STL) Common algorithms –fill –equal, mismatch –remove, remove_if –replace, replace_if –count, count_if –for_each –min_element –find, sort, binary_search –swap, merge, unique –set_intersection –heapsort
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.