Download presentation
Presentation is loading. Please wait.
Published byAmberly Fox Modified over 9 years ago
2
Template Lecture 11 Course Name: High Level Programming Language Year : 2010
3
3 Learning Outcomes At the end of this lecture, students are capable of: Understanding the concept of Template in C++ programming.
4
4 Outline Materi Why Use Templates C++ Function Templates C++ Class Templates
5
WHY USE TEMPLATES Create a type-safe collection class (for example, a stack) that can operate on data of any type. Add extra type checking for functions that would otherwise take void pointers. Encapsulate groups of operator overrides to modify type behavior (such as smart pointers). Most of these uses can be implemented without templates; however, templates offer several advantages:
6
WHY USE TEMPLATES (cont.) Templates are easier to write. You create only one generic version of your class or function instead of manually creating specializations. Templates can be easier to understand, since they can provide a straightforward way of abstracting type information. Templates are type-safe. Because the types that templates act upon are known at compile time, the compiler can perform type checking before errors occur.
7
Templates vs. Macros #define min(i, j) (((i) < (j)) ? (i) : (j)) and a template: template T min (T i, T j) { return ((i < j) ? i : j) }
8
Templates vs. Macros (cont.) Here are some problems with the macro: There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking. The i and j parameters are evaluated twice. For example, if either parameter has a postincremented variable, the increment is performed two times. Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
9
Templates vs. void pointers Many functions that are now implemented with void pointers can be implemented with templates. Void pointers are often used to allow functions to operate on data of an unknown type. When using void pointers, the compiler cannot distinguish types, so it cannot perform type checking or type-specific behavior such as using type-specific operators, operator overloading, or constructors and destructors.
10
Templates vs. void pointers With templates, create functions and classes that operate on typed data. The type looks abstracted in the template definition. However, at compile time the compiler creates a separate version of the function for each specified type. This enables the compiler to treat class and function templates as if they acted on specific types. Templates can also improve coding clarity, because you don't need to create special cases for complex types such as structures.
11
C++ Function Templates Approaches for functions that implement identical tasks for different data types – Naïve Approach – Function Overloading – Function Template Instantiating a Function Templates
12
Approach 1: Naïve Approach create unique functions with unique names for each combination of data types – difficult to keeping track of multiple function names – lead to programming errors
13
Example void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) { … } void PrintDouble( double d ) { … } PrintInt(sum); PrintChar(initial); PrintFloat(angle); To output the traced values, we insert:
14
Approach 2:Function Overloading (Review) The use of the same name for different C++ functions, distinguished from each other by their parameter lists Eliminates need to come up with many different names for identical tasks. Reduces the chance of unexpected results caused by using the wrong function name.
15
Example of Function Overloading void Print( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void Print( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void Print( float x ) { } Print(someInt); Print(someChar); Print(someFloat); To output the traced values, we insert:
16
Approach 3: Function Template A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types. Template FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
17
Example of a Function Template template void Print( SomeType val ) { cout << "***Debug" << endl; cout << "Value is " << val << endl; } Print (sum); Print (initial); Print (angle); To output the traced values, we insert: Template parameter (class, user defined type, built-in types) Template argument
18
Instantiating a Function Template When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template. Function (FunctionArgList) TemplateFunction Call
19
Summary of Three Approaches Naïve Approach Different Function Definitions Different Function Names Function Overloading Different Function Definitions Same Function Name Template Functions One Function Definition (a function template) Compiler Generates Individual Functions
20
Class Template A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types. Template ClassDefinition Class Template TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
21
Example of a Class Template template class GList { public: bool IsEmpty() const; bool IsFull() const; int Length() const; void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; void SelSort(); void Print() const; GList(); // Constructor private: int length; ItemType data[MAX_LENGTH]; }; Template parameter
22
Instantiating a Class Template Class template arguments must be explicit. The compiler generates distinct class types called template classes or generated classes. When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template.
23
Instantiating a Class Template // Client code GList list1; GList list2; GList list3; list1.Insert(356); list2.Insert(84.375); list3.Insert("Muffler bolt"); To create lists of different data types GList_int list1; GList_float list2; GList_string list3; template argument Compiler generates 3 distinct class types
24
Substitution Example class GList_int { public: void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; private: int length; ItemType data[MAX_LENGTH]; }; int
25
Function Definitions for Members of a Template Class template void GList ::Insert( /* in */ ItemType item ) { data[length] = item; length++; } //after substitution of float void GList ::Insert( /* in */ float item ) { data[length] = item; length++; }
26
Another Template Example: passing two parameters template class Stack {... }; Stack mystack; non-type parameter
27
27 Topic For Next Week Small Projects for two weeks Assignment: The last two week will be use to create a small project using concepts that we have learned for the past 10 sessions of classes. Group 2 or most 3 people, and propose a project to your lecturer to be approved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.