1 Using Templates COSC 1567 C++ Programming Lecture 10.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 4 Inheritance and Polymorphism.
Advertisements

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
1 Overloading Operators COSC 1567 C++ Programming Lecture 7.
Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Chapter 14: Overloading and Templates
VBA Modules, Functions, Variables, and Constants
Understanding Inheritance Object-Oriented Programming Using C++ Second Edition 9.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Using C++ Functions Object-Oriented Programming Using C++ Second Edition 4.
Guide To UNIX Using Linux Third Edition
Chapter 13: Object-Oriented Programming
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Review of C++ Programming Part II Sheng-Fang Huang.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
Chapter 8 More Object Concepts
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
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.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
1 Using C++ Functions Object-Oriented Programming Using C++ Second Edition 4.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
CS212: Object Oriented Analysis and Design
1 CSC241: Object Oriented Programming Lecture No 25.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Templates.
CLASSES AND OBJECTS Chapter 3 : constructor, Separate files, validating data.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Constructors and Destructors
Chapter 14 Templates C++ How to Program, 8/e
CS212: Object Oriented Analysis and Design
User-Defined Functions
Understanding Inheritance
Object-Oriented Programming Using C++ Second Edition
Object-Oriented Programming Using C++ Second Edition
Constructors and Destructors
Java Programming Language
Presentation transcript:

1 Using Templates COSC 1567 C++ Programming Lecture 10

2 Objectives The usefulness of function templates The structure of function templates Overload function templates Create function templates with multiple data types Create function templates with multiple parameterized types

3 Objectives Override a function template’s implicit type Use multiple explicit types when you call a function template Use function templates with classes Template classes and how to create them Container classes and how to create them

4 Understanding the Usefulness of Function Templates The C++ compiler determines the function’s argument types when the function is created and compiled Once the function is created, the argument types remain fixed Overloading involves writing two or more functions with the same name but different argument lists It allows you to employ polymorphism, using a consistent message that acts appropriately with different objects A reverse() function might change the sign of a number if a numeric variable is passed to it

5 Understanding the Usefulness of Function Templates

6 Creating Function Templates In C++, you can create functions that use variable types These function templates serve as an outline, or template, for a group of functions that differ in the types of parameters they use A group of functions that generates from the same template is often called a family of functions In a function template, at least one argument is generic, or parameterized, meaning that one argument can stand for any number of C++ types C++ also allows you to define macros, which permit generic substitution

7 Creating Function Templates Before you code a function template, you must include a template definition with the following information: –The keyword template –A left angle bracket (<) –A list of generic types, separated with commas if more than one type is needed –A right angle bracket (>) Each generic type in the list of generic types has two parts: –The keyword class –An identifier that represents the generic type

8 Creating Function Templates Using the keyword class in the template definition does not necessarily mean that T stands for a programmer-created class type, but it may Ex11-1

9 Using Multiple Arguments to Function Templates Function templates can support multiple parameters

10 Using Multiple Arguments to Function Templates Define a function that displays the smallest of any of three same-type arguments it receives Ex10-1.cpp

11 Overloading Function Templates You overload functions when you create functions with the same name but with different argument lists You can overload function templates, as long as each version of the function takes different arguments, allowing the compiler to distinguish between them Ex10-2.cpp

12 A main() Function that Uses the Overloaded invert() Function Template

13 Overloading Function Templates Overload the displaySmallest() function template to accept two as well as three arguments Ex10-3.cpp

14 Using More than One Type in a Function Template Like other functions, function templates can use variables of multiple types Suppose you want to create a function template that displays a value a given number of times The value could be any type, but the number of times to repeat the value is an integer It is perfectly legal to include some nonparameterized types in the function argument list, along with the parameterized ones

15 RepeatValue Program Ex10-4.cpp

16 Using More than One Parameterized Type in a Function Template To create a function template that employs multiple generic types, you simply use a unique type identifier for each type Two generic types, T and U, are defined The first parameterized type, T, can stand for any type The second type, U, can stand for the same type, or any other type Figure includes a demonstration main() function that passes a variety of arguments to whichIsLarger(), and Figure shows the results

17 whichIsLarger() Function and main() Program Ex10-5.cpp

18 Explicitly Specifying the Type in a Function Template When you call a function template, the arguments to the function dictate the types to be used To override a deduced type, when you call a function template you can explicitly code a type within angle brackets immediately following the function name in the function call You explicitly name a type by using the type name

19 Program that Uses an Explicit Type for a Function’s Parameterized Type Ex10-6.cpp The above calls the function template three times, using an integer, a double, and a double converted to an integer, respectively

20 Using Multiple Explicit Types in a Function Template You can use multiple explicit types when you call a template function If you want the return value of a template function sometimes to be the same type as the argument, and sometimes to be a different type, write the function template with two parameterized types Additionally, you can exercise the option to explicitly name one or both types

21 Using Multiple Explicit Types in a Function Template The main() program in Figure uses the function in several ways: –Explicitly codes int for the T type and passes an integer to implicitly assign the U type –Explicitly codes int for the T type and passes a double to implicitly assign the U type –Explicitly codes int for the T type and explicitly codes a double for the U type –Explicitly codes int for both T and U

22 Using Multiple Explicit Types in a Function Template Figure shows the output of the program in Figure The explanation of the output is as follows: –When tripleVal() receives the integer 22 as an argument, triples it, and returns the integer result, the output is 66 –When tripleVal() receives the double 8.88 as an argument, triples it to 26.64, stores the result in an integer, and returns the integer result, the output is the truncated result, 26. This is true whether tripleVal() receives 8.88 as a double implicitly or explicitly –When 8.88 is explicitly received as an integer, it receives an 8. The output tripled value is 24

23 Using Multiple Explicit Types in a Function Template Ex10-7.cpp

24 Using Function Templates with Class Objects When programming in an object-oriented environment, you naturally want your function templates to work with class objects as well as with scalar variables Function templates work just as well with classes as they do with simple data types Your only additional responsibility is to ensure that any operations used within the function template have been defined for the class objects passed to the function templates

25 The PhoneCall Class Ex10-8.cpp

26 Using Function Templates with Class Objects Figure shows a PhoneCall class containing private data members that store the phone number, length of call, and code The program in Figure declares a PhoneCall object and provides initial values for its fields Create an Inventory class The class includes an overloaded insertion operator and an overloaded less than operator

27 Using Function Templates with Class Objects Ex10-8.cpp Ex10-9.cpp

28 Using Template Classes Function templates allow you to create generic functions that have the same bodies but can take different data types as parameters In some situations classes are similar and you want to perform very similar operations with them If you need to create several similar classes, you might consider developing a template class, a class in which at least one type is generic or parameterized

29 Using Template Classes The template class provides the outline for a family of similar classes To create a template class, you begin with the template definition, just as you do with a function template The class in Figure is named Number Its private member, theNumber, may be of any type

30 The Number Class Definition

31 Creating a Complete Class Template Figure shows the class definition for the Number class, along with the implementation of the Number class functions You can see in Figure that the definition template also is required before the definition of the displayNumber() function, so as to identify the T in the class name, Number The displayNumber() function always displays “Number #” just before the value of theNumber Figure contains a main() function that declares three Number objects constructed using integer, double, and character argument, respectively

32 Creating a Complete Class Template

33 Creating a Complete Class Template Ex10-10.cpp

34 Using Container Classes A container class is a template class that has been written to perform common class tasks; the purpose of container classes is to manage groups of other classes A common programming task that is used in a variety of applications is the construction of a linked list A linked list is a chain of objects, each of which consists of at least two parts—the usual components of the object itself and a pointer to another object

35 Using Container Classes The diagram in Figure illustrates a linked list of Students No matter what types of objects are linked, procedures must be developed to establish links between objects and to insert new objects into appropriate spots within the linked list The procedures include assigning the correct linking pointer values to the new list members Other common procedures are deleting a member from the list, reordering a list, and retrieving and displaying the objects from a list

36 A Student Linked List

37 Creating an Array Template Class When you create an array, you create a list of same-type objects at adjacent memory locations You perform many standard operations on array data, no matter what type is involved You can create a generic Array class with two private data members: a pointer to the beginning of the array, and an integer representing the size of the array 11

38 The Array Class

39 Creating an Array Template Class The Array class constructor assigns the argument’s array address to the Array class array address, and assigns the argument’s array size to the Array class member size The showList() function displays each element of the Array, from element 0 up through one less than size Figure shows a Book class, and Figure shows a Client class Neither contains anything unusual; you have created many similar classes

40 The Book Class

41 The Client Class

42 Creating an Array Template Class Figure shows a main() function that contains several types of arrays The program in Figure is divided into four parts, which are: –An array named someInts is initialized with three integers –An array named someDoubles is initialized with four doubles –A two-element Book array uses the Book class shown in Figure The two Books receive values through the setBook() function –A four-element Clients array uses the Client class shown in Figure The Clients receive values through the setClient() function

43 Program Using the Array Container Class Ex10-11.cpp When using the showList() function, each list appears correctly no matter how many elements the array contains

More examples Ex10-12.cpp Ex10-13.cpp Ex10-14.cpp Ex10-15.cpp 44

45 Summary When the logic of several functions is similar, writing the code to overload the functions becomes tedious A function template is a function that serves as an outline, or template, for a group of functions that differ in the types of parameters they use You can overload function templates, as long as each version of the function takes different arguments, allowing the compiler to distinguish between them

46 Summary In addition to a parameterized variable, function templates can contain multiple arguments and internal variables that are not generic Function templates can have multiple parameterized types; you use a unique type identifier for each type When you call a function template, the compiler implicitly deduces the correct types to use within the function template 11

47 Summary You can use multiple explicit types when you call a function template Function templates work just as well with classes as they do with simple data types—as long as you define all operations for the classes you use within the function template A template class is a class in which at least one type is generic or parameterized It provides the outline for a family of similar classes 11

48 Summary When you create a class template, you use the template definition prior to the class and prior to each function you write A container class is a template that has been written to perform common class tasks; the purpose of container classes is to manage groups of other classes You create container class templates to speed up the development process for applications that require similar tasks 11