14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.

Slides:



Advertisements
Similar presentations
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Functions.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
 2006 Pearson Education, Inc. All rights reserved Generics.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
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.
You gotta be cool. C++ ? C++ Standard Library Header Files Inline Functions References and Reference Parameters Default Arguments and Empty Parameter.
Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10.
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
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.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
1 CSC241: Object Oriented Programming Lecture No 25.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 22 - C++ Templates Outline 22.1Introduction.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
 Templates enable us to define generic classes and functions and thus provides support for generic programming. Generic types are used as parameters.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
計算機程式語言 Lecture 03-1 國立台灣大學生物機電系 林達德 3 3 Introduction to Classes and Objects.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CHAPTER 07 Arrays and Vectors (part II). OBJECTIVES In this part you will learn:  To pass arrays to functions.  Basic searching techniques.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 3 Part II. 3.8 Placing a Class in a Separate File for Reusability.cpp file is known as a source-code file. Header files ◦ Separate files in which.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
CLASSES AND OBJECTS Chapter 3 : constructor, Separate files, validating data.
 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.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
 2006 Pearson Education, Inc. All rights reserved Templates.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
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.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
Hightlights C++ Template C++ Number Systems.
Chapter 18 Introduction to Custom Templates
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Introduction to Classes and Objects
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.
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.
Presentation transcript:

14 Templates

OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.  To distinguish between function templates and function- template specializations.  To use class templates to create a group of related types.  To distinguish between class templates and class- template specializations.  To overload function templates.

14.1 Introduction Function templates and class templates – Enable programmers to specify, within a single code segment, an entire range of related functions and related classes Called function-template specializations and class-template specializations, respectively – This technique is called Generic programming – We can write a single function template for an array-sort function and have c++ generate separate function-template specializations that will sort int arrays, float arrays, string arrays and so on.

Software Engineering Observation 14.1 Most C++ compilers require the complete definition of a template to appear in the client source-code file that uses the template. For this reason and for reusability, templates are often defined in header files, which are then #included into the appropriate client source-code files. For class templates, this means that the member functions are also defined in the header file.

14.2 Function Templates Function Templates – Used to produce overloaded functions that perform identical operations on different types of data Programmer writes a single function-template definition Compiler generates separate object-code functions (function- template specializations) based on argument types in calls to the function template

14.2 Function Templates (Cont.) Function-template definitions – Preceded by a template header Keyword template List of template parameters – Enclosed in angle brackets ( ) – Each template parameter is preceded by keyword class or keyword typename (both are interchangeable) – Used to specify types of arguments to, local variables in and return type of the function template Examples – template

14.2 Function Templates (Cont.) template myType GetMax (myType a, myType b) { return (a>b?a:b); } Creates a template function that returns the greater of two objects Template function with myType as its template parameter The template parameter type hasn’t been defined but that can be used in the function as if it is a regular type

14.2 Function Templates (Cont.) int x,y; GetMax (x,y); To use this function, we use the following function call. The compiler uses the template to generate a function replacing each appearance of myType by the type passed as the actual template paramter, int in this case.

14.2 Function Templates (Cont.) // function template #include using namespace std; template T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax (i,j); n=GetMax (l,m); cout << k << endl; cout << n << endl; return 0; } Output: 6 10

14.2 Function Templates (Cont.) Getmax is used twice First time with arguments of type int Second time with arguments of type long Compiler instantiates and calls the appropriate function Type T is also used to declare object of type T compiler can also find out automatically which data type to instantiate int i,j; GetMax (i,j);

14.2 Function Templates (Cont.) // function template II #include using namespace std; template T GetMax (T a, T b) { return (a>b?a:b); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << k << endl; cout << n << endl; return 0; }

14.2 Function Templates (Cont.) int i; long l; k = GetMax (i,l); This would not be correct

14.2 Function Templates (Cont.) template T GetMin (T a, U b) { return (a<b?a:b); } Function templates can have more than one type parameter This function accepts two parameters of different types and returns an object of the same type as the first argument

Common Programming Error 14.1 Not placing keyword class or keyword typename before each type template parameter of a function template is a syntax error.

Outline fig14_01.cpp (1 of 2) Type template parameter T specified in template header

Outline fig14_01.cpp (2 of 2) Creates a function-template specialization of printArray where int replaces T Creates a function-template specialization of printArray where double replaces T Creates a function-template specialization of printArray where char replaces T

Common Programming Error 14.2 If a template is invoked with a user-defined type, and if that template uses functions or operators (e.g., ==, +, <=) with objects of that class type, then those functions and operators must be overloaded for the user-defined type. Forgetting to overload such operators causes compilation errors.

Performance Tip 14.1 Although templates offer software-reusability benefits, remember that multiple function-template specializations and class-template specializations are instantiated in a program (at compile time), despite the fact that the template is written only once. These copies can consume considerable memory. This is not normally an issue, though, because the code generated by the template is the same size as the code the programmer would have written to produce the separate overloaded functions.

14.3 Overloading Function Templates A function template may be overloaded – Other function templates that specify the same name but different parameters – Nontemplate functions that specify the same name but different parameters – The compiler chooses the best function or specialization to match the function call A nontemplate function is chosen over a template specialization in case of a tie Otherwise, multiple matches results in a compilation error (the compiler considers the function call to be an ambiguous function call )

Common Programming Error 14.3 If no matching function definition can be found for a particular function call, or if there are multiple matches, the compiler generates an error.

14.4 Class Templates Class templates (or parameterized types) – Class-template definitions are preceded by a header Such as template – Type parameter T can be used as a data type in member functions and data members – Additional type parameters can be specified using a comma-separated list As in template

14.4 Class Templates template class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } }; This class stores two elements of any valid type mypair myobject (115, 36); mypair myfloats (3.0, 2.18);

14.4 Class Templates // class templates #include using namespace std; template class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template T mypair ::getmax () { T retval; retval = a>b? a : b; return retval; } int main () { mypair myobject (100, 75); cout << myobject.getmax(); return 0; } template T mypair ::getmax ()

Software Engineering Observation 14.2 Class templates encourage software reusability by enabling type-specific versions of generic classes to be instantiated.

Outline Stack.h (1 of 3) Create class template Stack with type parameter T Member functions that use type parameter T in specifying function parameters

Outline Stack.h (2 of 3) Data member stackPtr is a pointer to a T Member-function template definitions that appear outside the class-template definition begin with the template header

Outline Stack.h (3 of 3)

Outline fig14_03.cpp (1 of 3) Create class-template specialization Stack where type double is associated with type parameter T

Outline fig14_03.cpp (2 of 3) Create class-template specialization Stack where type int is associated with type parameter T

Outline fig14_03.cpp (3 of 3)

Outline fig14_04.cpp (1 of 3) Use a function template to process Stack class-template specializations

Outline fig14_04.cpp (2 of 3)

Outline fig14_04.cpp (3 of 3)

14.5 Nontype Parameters and Default Types for Class Templates Nontype template parameters – Can have default arguments – Are treated as const s – Example Template header: template Declaration: Stack salesFigures; Type parameters can have default arguments too – Example Template header: template Declaration: Stack<> jobDescriptions;

Performance Tip 14.2 When appropriate, specify the size of a container class (such as an array class or a stack class) at compile time (possibly through a nontype template parameter). This eliminates the execution-time overhead of using new to create the space dynamically.

Software Engineering Observation 14.3 Specifying the size of a container at compile time avoids the potentially fatal execution-time error if new is unable to obtain the needed memory.

Quiz (Simple Encryption) Some information on the Internet may be encrypted with a simple algorithm known as "rot13," which rotates each character by 13 positions in the alphabet. Thus, 'a' corresponds to 'n', and 'x' corresponds to 'k'. rot13 is an example of symmetric key encryption. With symmetric key encryption, both the encrypter and decrypter use the same key. – Write a program that encrypts a message using rot13. – Write a program that decrypts the scrambled message using 13 as the key.