1 using templates cosc 1567 c++ programming lecture 10

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

Upload: virginia-mclaughlin

Post on 14-Jan-2016

218 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Using Templates COSC 1567 C++ Programming Lecture 10

11

Using TemplatesUsing Templates

COSC 1567COSC 1567

C++ ProgrammingC++ Programming

Lecture 10

Page 2: 1 Using Templates COSC 1567 C++ Programming Lecture 10

22

ObjectivesObjectives

• 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

Page 3: 1 Using Templates COSC 1567 C++ Programming Lecture 10

33

ObjectivesObjectives

• 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

Page 4: 1 Using Templates COSC 1567 C++ Programming Lecture 10

44

Understanding the Usefulness Understanding the Usefulness of Function Templatesof 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

Page 5: 1 Using Templates COSC 1567 C++ Programming Lecture 10

55

Understanding the Usefulness Understanding the Usefulness of Function Templatesof Function Templates

Page 6: 1 Using Templates COSC 1567 C++ Programming Lecture 10

66

Creating Function TemplatesCreating 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

Page 7: 1 Using Templates COSC 1567 C++ Programming Lecture 10

77

Creating Function TemplatesCreating 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

Page 8: 1 Using Templates COSC 1567 C++ Programming Lecture 10

88

Creating Function TemplatesCreating 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

Page 9: 1 Using Templates COSC 1567 C++ Programming Lecture 10

99

Using Multiple Arguments Using Multiple Arguments to Function Templatesto Function Templates

• Function templates can support multiple parameters

Page 10: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1010

Using Multiple Arguments Using Multiple Arguments to Function Templatesto Function Templates

• Define a function that displays the smallest of any of three same-type arguments it receives

Ex10-1.cpp

Page 11: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1111

Overloading Function Overloading Function TemplatesTemplates

• 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

Page 12: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1212

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

Function TemplateFunction Template

Page 13: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1313

Overloading Function Overloading Function TemplatesTemplates

• Overload the displaySmallest() function template to accept two as well as three arguments

Ex10-3.cpp

Page 14: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1414

Using More than One Type Using More than One Type in a Function Templatein 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

Page 15: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1515

RepeatValue ProgramRepeatValue Program Ex10-4.cpp

Page 16: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1616

Using More than One Using More than One Parameterized Type in a Parameterized Type in a

Function TemplateFunction 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 11-12 includes a demonstration main()

function that passes a variety of arguments to whichIsLarger(), and Figure 11-13 shows the results

Page 17: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1717

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

Page 18: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1818

Explicitly Specifying the Type Explicitly Specifying the Type in a Function Templatein 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

Page 19: 1 Using Templates COSC 1567 C++ Programming Lecture 10

1919

Program that Uses an Explicit Program that Uses an Explicit Type for a Function’s Type for a Function’s Parameterized TypeParameterized 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

Page 20: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2020

Using Multiple Explicit Types Using Multiple Explicit Types in a Function Templatein 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

Page 21: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2121

Using Multiple Explicit Types Using Multiple Explicit Types in a Function Templatein a Function Template

• The main() program in Figure 11-17 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

Page 22: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2222

Using Multiple Explicit Types Using Multiple Explicit Types in a Function Templatein a Function Template

• Figure 11-18 shows the output of the program in Figure 11-17

• 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

Page 23: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2323

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

Page 24: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2424

Using Function Templates Using Function Templates with Class Objectswith 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

Page 25: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2525

The PhoneCall ClassThe PhoneCall Class Ex10-8.cpp

Page 26: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2626

Using Function Templates Using Function Templates with Class Objectswith Class Objects

• Figure 11-20 shows a PhoneCall class containing private data members that store the phone number, length of call, and code

• The program in Figure 11-21 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

Page 27: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2727

Using Function Templates Using Function Templates with Class Objectswith Class Objects Ex10-8.cpp

Ex10-9.cpp

Page 28: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2828

Using Template ClassesUsing 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

Page 29: 1 Using Templates COSC 1567 C++ Programming Lecture 10

2929

Using Template ClassesUsing 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 11-24 is named Number• Its private member, theNumber, may be of any type

Page 30: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3030

The Number Class DefinitionThe Number Class Definition

Page 31: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3131

Creating a Complete Class Creating a Complete Class TemplateTemplate

• Figure 11-25 shows the class definition for the Number class, along with the implementation of the Number class functions

• You can see in Figure 11-25 that the definition template<class T> also is required before the definition of the displayNumber() function, so as to identify the T in the class name, Number<T>

• The displayNumber() function always displays “Number #” just before the value of theNumber

• Figure 11-26 contains a main() function that declares three Number objects constructed using integer, double, and character argument, respectively

Page 32: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3232

Creating a Complete Class Creating a Complete Class TemplateTemplate

Page 33: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3333

Creating a Complete Class Creating a Complete Class TemplateTemplate Ex10-10.cpp

Page 34: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3434

Using Container ClassesUsing 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

Page 35: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3535

Using Container ClassesUsing Container Classes

• The diagram in Figure 11-28 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

Page 36: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3636

A Student Linked ListA Student Linked List

Page 37: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3737

Creating an Array Template Creating an Array Template ClassClass

• 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

Page 38: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3838

The Array ClassThe Array Class

Page 39: 1 Using Templates COSC 1567 C++ Programming Lecture 10

3939

Creating an Array Template Creating an Array Template ClassClass

• 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 11-30 shows a Book class, and Figure 11-31 shows a Client class

• Neither contains anything unusual; you have created many similar classes

Page 40: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4040

The Book ClassThe Book Class

Page 41: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4141

The Client ClassThe Client Class

Page 42: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4242

Creating an Array Template Creating an Array Template ClassClass

• Figure 11-32 shows a main() function that contains several types of arrays

• The program in Figure 11-32 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 11-30. The two Books receive values through the setBook() function

– A four-element Clients array uses the Client class shown in Figure 11-31. The Clients receive values through the setClient() function

Page 43: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4343

Program Using the Array Container ClassProgram Using the Array Container ClassEx10-11.cpp

• When using the showList() function, each list appears correctly no matter how many elements the array contains

Page 44: 1 Using Templates COSC 1567 C++ Programming Lecture 10

More examplesMore examples

• Ex10-12.cpp

• Ex10-13.cpp

• Ex10-14.cpp

• Ex10-15.cpp

4444

Page 45: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4545

SummarySummary

• 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

Page 46: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4646

SummarySummary

• 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

Page 47: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4747

SummarySummary

• 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

Page 48: 1 Using Templates COSC 1567 C++ Programming Lecture 10

4848

SummarySummary

• 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