Template Lecture 11 Course Name: High Level Programming Language Year : 2010.

Slides:



Advertisements
Similar presentations
Lecture 18: 4/11/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 14: Overloading and Templates
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Data Structures Lecture-12 : STL Azhar Maqsood NUST Institute of Information Technology (NIIT)
Templates Zhen Jiang West Chester University
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
1 Chapter 17-1 Templates and Exceptions Dale/Weems.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CS212: Object Oriented Analysis and Design Lecture 9: Function Overloading in C++
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Copyright 2006, The Ohio State University Introduction to C++ Templates l C++ Function Templates l C++ Class Templates.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Chapter 17 Templates and Exceptions Dale/Weems.
Computer Science and Software Engineering University of Wisconsin - Platteville 5. Template Yan Shi CS/SE 2630 Lecture Notes.
1 Chapter 17 Templates and Exceptions Dale/Weems/Headington.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Ders Notu 8 - Template İçerik 11.1 Giriş 11.2 Fonksiyon Template ları 11.3 Overloading Fonksiyon Templates.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
 2006 Pearson Education, Inc. All rights reserved Templates.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
Overloading C++ supports the concept of overloading Two main types
Programming with ANSI C ++
C++ Templates.
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Review: Two Programming Paradigms
Generic programming – Function template
CS212: Object Oriented Analysis and Design
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Object Oriented Programming Using C++
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Yan Shi CS/SE 2630 Lecture Notes
Lab4 problems More about templates Some STL
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Lecture 8: Introduction to C++ Templates and Exceptions
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Template Lecture 11 Course Name: High Level Programming Language Year : 2010

3 Learning Outcomes At the end of this lecture, students are capable of: Understanding the concept of Template in C++ programming.

4 Outline Materi Why Use Templates C++ Function Templates C++ Class Templates

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:

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.

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) }

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.

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.

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.

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

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

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:

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.

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:

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

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

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

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

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

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

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.

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

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

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++; }

Another Template Example: passing two parameters template class Stack {... }; Stack mystack; non-type parameter

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.