48
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter Chapter 17 17 Templates Templates

Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates

  • View
    244

  • Download
    0

Embed Size (px)

Citation preview

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 17Chapter 17TemplatesTemplates

Slide 17- 2

OverviewOverview

17.1 Templates for Algorithm 17.1 Templates for Algorithm

AbstractionAbstraction

17.2 Templates for Data Abstraction17.2 Templates for Data Abstraction

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

17.117.1Templates for Algorithm Templates for Algorithm

AbstractionAbstraction

Slide 17- 4

Templates for Algorithm AbstractionTemplates for Algorithm AbstractionFunction definitions often use application Function definitions often use application specific adaptations of more general algorithmsspecific adaptations of more general algorithms For example: The general algorithm used in For example: The general algorithm used in

swap_values could swap variables of any type:swap_values could swap variables of any type:void swap_values(type_of_var& v1, void swap_values(type_of_var& v1,

type_of_var& v2) type_of_var& v2) {{ type_of_var temp;type_of_var temp; temp = v1;temp = v1;

v1 = v2;v1 = v2; v2 = temp;v2 = temp; }}

Slide 17- 5

swap_values for charswap_values for char

Here is a version of swap_values to swap Here is a version of swap_values to swap character variables:character variables: void swap_values(char& v1, char& v2)void swap_values(char& v1, char& v2)

{{ char temp; char temp;

temp = v1; temp = v1; v1 = v2; v1 = v2;

v2 = temp; v2 = temp; } }

Now We Want to Swap IntegersNow We Want to Swap Integers Up until now, we would have to write a Up until now, we would have to write a

new function or at least swap char to nt..new function or at least swap char to nt.. void swap_values(int& v1, int& v2)void swap_values(int& v1, int& v2)

{{ int temp; int temp;

temp = v1; temp = v1; v1 = v2; v1 = v2;

v2 = temp; v2 = temp; } }

Why do all this rewriting?Why do all this rewriting?

Slide 17- 7

A General swap_valuesA General swap_valuesIt would be nicer to write one function that could be used It would be nicer to write one function that could be used for any typefor any type

A generalized version of swap_values might beA generalized version of swap_values might be void swap_values(type_of_var& v1, type_of_var& v2)void swap_values(type_of_var& v1, type_of_var& v2)

{ { type_of_var temp; type_of_var temp;

temp = v1; temp = v1; v1 = v2; v1 = v2;

v2 = temp; v2 = temp; } }

This function, if type_of_var could accept any type, This function, if type_of_var could accept any type, could be used to swap values of any typecould be used to swap values of any type

Slide 17- 8

A A C++ function templateC++ function template will allow swap_values will allow swap_valuesto swap values of two variables of the same to swap values of two variables of the same typetype Example: Example:

template<class T> template<class T> void swap_values(T& v1, T& v2) void swap_values(T& v1, T& v2) { { T temp; T temp; temp = v1; temp = v1; v1 = v2; v1 = v2; v = temp; v = temp; } }

Template prefix

Template parameter

Templates for FunctionsTemplates for Functions

Slide 17- 9

Template DetailsTemplate Detailstemplate<class T> is the template prefixtemplate<class T> is the template prefix Tells compiler that the declaration or definition Tells compiler that the declaration or definition

that follows is a templatethat follows is a template Tells compiler that T is a type parameterTells compiler that T is a type parameter

class means type in this context class means type in this context (typename could replace class but class is (typename could replace class but class is usually used)usually used)

T can be replaced by any type argumentT can be replaced by any type argument(whether the type is a class or not)(whether the type is a class or not)

A template overloads the function name by A template overloads the function name by replacing T with the type used in a function callreplacing T with the type used in a function call

Slide 17- 10

Calling a Template FunctionCalling a Template FunctionCalling a function defined with a template is Calling a function defined with a template is identical to calling a normal functionidentical to calling a normal function Example: Example:

To call the template version of swap_values To call the template version of swap_values char s1, s2; // for the char version char s1, s2; // for the char version

int i1, i2; // for the int versionint i1, i2; // for the int version

… … swap_values(s1, s2);swap_values(s1, s2); swap_values(i1, i2); swap_values(i1, i2);

The compiler checks the argument types and The compiler checks the argument types and generates an appropriate version of swap_valuesgenerates an appropriate version of swap_values

Slide 17- 11

Templates and DeclarationsTemplates and DeclarationsA function template may also have a separateA function template may also have a separatedeclarationdeclaration The template prefix and type parameter are used The template prefix and type parameter are used Depending on your compilerDepending on your compiler

You may, or may not, be able to separate declaration You may, or may not, be able to separate declaration and definitions of template functions just as you do with and definitions of template functions just as you do with regular functionsregular functions

To be safe, place template function definitions in the same To be safe, place template function definitions in the same file where they are used…with no declarationfile where they are used…with no declaration

A file included with #include is, in most cases, A file included with #include is, in most cases, equivalent to being "in the same file“equivalent to being "in the same file“

This means including the .cpp file or .h file with This means including the .cpp file or .h file with implementation codeimplementation code

Slide 17- 12

T is the traditional name for the type parameterT is the traditional name for the type parameter Any valid, non-keyword, identifier can be usedAny valid, non-keyword, identifier can be used "VariableType" could be used"VariableType" could be used

template <class VariableType> template <class VariableType> void swap_values(VariableType& v1, void swap_values(VariableType& v1, VariableType& v2) VariableType& v2) { { VariableType temp; VariableType temp; … … } }

The Type Parameter TThe Type Parameter T

Slide 17- 13

Slide 17- 14

Templates with Templates with Multiple ParametersMultiple Parameters

Function templates may use more than Function templates may use more than oneoneparameterparameter Example:Example:

template<class T1, class T2> template<class T1, class T2>

All parameters must be used in the template All parameters must be used in the template functionfunction

Slide 17- 15

Algorithm AbstractionAlgorithm Abstraction

Using a template function we can express Using a template function we can express more general algorithms in C++more general algorithms in C++

Algorithm abstraction means expressing Algorithm abstraction means expressing algorithms in a very general way so we can algorithms in a very general way so we can

ignore incidental detailignore incidental detail This allows us to concentrate on the This allows us to concentrate on the

substantive part of the algorithmsubstantive part of the algorithm

Slide 17- 16

Program Example:Program Example:A Generic Sorting FunctionA Generic Sorting Function

The sort function defined in the next uses an The sort function defined in the next uses an algorithm that does not depend on the base algorithm that does not depend on the base type of the arraytype of the arraysort uses two helper functions sort uses two helper functions index_of_smallest also uses a general index_of_smallest also uses a general

algorithm and could be defined with a algorithm and could be defined with a template template

swap_values has already been adapted as a swap_values has already been adapted as a templatetemplate

A Generic AlgorithmA Generic Algorithm

void sort(int a[], int number_usedvoid sort(int a[], int number_used)){ int index_of_next_smallest;{ int index_of_next_smallest; for (int index = 0; index < number_used -1; for (int index = 0; index < number_used -1;

index++)index++) { index_of_next_smallest = { index_of_next_smallest = index_of_smallest(a, index, index_of_smallest(a, index,

number_used);number_used); swap_values(a[index], swap_values(a[index],

a[index_of_next_smallest]); }}a[index_of_next_smallest]); }} The same algorithm could be used to sort an array The same algorithm could be used to sort an array

of any typeof any type

All three functions, defined with templates All three functions, defined with templates

in C++, are demonstrated in next 3 slidesin C++, are demonstrated in next 3 slides

Slide 17- 19

Slide 17- 20

Slide 17- 21

Slide 17- 22

Templates and OperatorsTemplates and OperatorsThe function index_of_smallest compares The function index_of_smallest compares items in an array using the < operatoritems in an array using the < operator If a template function uses an operator, If a template function uses an operator,

such as <, that operator must be defined such as <, that operator must be defined for the types being comparedfor the types being compared

If a class type has the < operator If a class type has the < operator overloaded for the class, then an array of overloaded for the class, then an array of objects of the class could be sorted with objects of the class could be sorted with function template sortfunction template sort

Slide 17- 23

Defining TemplatesDefining TemplatesWhen defining a template it is a good idea…When defining a template it is a good idea… To start with an ordinary function that To start with an ordinary function that

accomplishes the task with one typeaccomplishes the task with one type

It is often easier to deal with a concrete It is often easier to deal with a concrete case rather than the general casecase rather than the general case

Then debug the ordinary functionThen debug the ordinary function Next convert the function to a template by Next convert the function to a template by

replacing type names with a type replacing type names with a type parameterparameter

Slide 17- 24

Inappropriate Types for Inappropriate Types for TemplatesTemplates

Templates can be used for any type for which Templates can be used for any type for which the code in the function makes sensethe code in the function makes sense swap_values swaps individual objects of a typeswap_values swaps individual objects of a type However, this code would not work, because the However, this code would not work, because the

assignment operator used in swap_values does assignment operator used in swap_values does not work with arrays:not work with arrays: int a[10], b[10]; int a[10], b[10]; <code to fill the arrays> <code to fill the arrays> swap_values(a, b); swap_values(a, b);

Slide 17- 25

Section 17.1 ConclusionSection 17.1 Conclusion

Can youCan you Identify a template prefix?Identify a template prefix? Identify a parameter type in a template Identify a parameter type in a template

prefix?prefix? Compare and contrast function Compare and contrast function

overloading with the use of templates?overloading with the use of templates?

What additional complexities are What additional complexities are involved when class types are involved involved when class types are involved as parameter types?as parameter types?

Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

17.217.2Templates for Data Templates for Data

AbstractionAbstraction

Slide 17- 27

Templates for Data AbstractionTemplates for Data AbstractionClass definitions can also be made more Class definitions can also be made more general with templatesgeneral with templates The syntax for class templates is basically The syntax for class templates is basically

the same as for function templatesthe same as for function templates

template<class T> comes before the template<class T> comes before the template definitiontemplate definition

Type parameter T is used in the class Type parameter T is used in the class definition just like any other type definition just like any other type

Type parameter T can represent any Type parameter T can represent any typetype

Slide 17- 28

A Class TemplateA Class TemplateThe following is a class templateThe following is a class template An object of this class contains a pair of An object of this class contains a pair of

values of type Tvalues of type T template <class T>template <class T>

class Pairclass Pair{{ public: public: Pair( ); Pair( ); Pair( T first_value, T second_value); Pair( T first_value, T second_value);

… … continued on next slide continued on next slide

Slide 17- 29

Template Class Pair (cont.)Template Class Pair (cont.)void set_element( int position, T value);void set_element( int position, T value);

//Precondition: position is 1 or 2 //Precondition: position is 1 or 2 //Postcondition: position indicated is set to value //Postcondition: position indicated is set to value

T get_element( int position) const;T get_element( int position) const; // Precondition: position is 1 or 2 // Precondition: position is 1 or 2 // Returns value in position indicated // Returns value in position indicated

private:private: T first; T first; T second; T second;};};

Slide 17- 30

Declaring Declaring Template Class ObjectsTemplate Class Objects

Once the class template is defined, objects Once the class template is defined, objects may be declaredmay be declared Declarations must indicate what type is to be Declarations must indicate what type is to be

used for Tused for T Example: To declare an object so it can hold Example: To declare an object so it can hold

a pair of integers:a pair of integers: Pair<int> score; Pair<int> score;

or for a pair of characters:or for a pair of characters: Pair<char> seats; Pair<char> seats;

Slide 17- 31

Using the ObjectsUsing the ObjectsAfter the declaration, objects based on a After the declaration, objects based on a template class are used just like any other template class are used just like any other objectsobjects Continuing the previous example:Continuing the previous example:

score.set_element(1,3); score.set_element(1,3); score.set_element(2,0); score.set_element(2,0); seats.set_element(1, 'A'); seats.set_element(1, 'A');

Slide 17- 32

Defining the Member FunctionsDefining the Member FunctionsMember functions of a template class are Member functions of a template class are definedthe same way as member functions of definedthe same way as member functions of ordinaryordinaryclassesclasses The only difference is that the member The only difference is that the member

function definitions are themselves templatesfunction definitions are themselves templates

Slide 17- 33

This is a definition of the constructor for classThis is a definition of the constructor for classPair that takes two argumentsPair that takes two arguments

template<class T> template<class T> Pair<T>::Pair(T first_value, T second_value) Pair<T>::Pair(T first_value, T second_value) : first(first_value), : first(first_value),

second(second_value)second(second_value) { //No body needed due to initialization { //No body needed due to initialization above }above } The class name includes <T>The class name includes <T>

Defining a Pair ConstructorDefining a Pair Constructor

Slide 17- 34

Defining set_element Defining set_element Here is a definition for set_element in the Here is a definition for set_element in the template class Pairtemplate class Pair

void Pair<T>::set_element(int position, T value)void Pair<T>::set_element(int position, T value){{ if (position = = 1) if (position = = 1) first = value; first = value; else if (position = = 2) else if (position = = 2) second = value; second = value; else else … …}}

Slide 17- 35

Template Class NamesTemplate Class Names as Parameters as Parameters

The name of a template class may be used The name of a template class may be used as the type of a function parameteras the type of a function parameter Example: To create a parameter of type Example: To create a parameter of type

Pair<int>:Pair<int>:

int add_up( const Pair<int>& the_pair); int add_up( const Pair<int>& the_pair); //Returns the sum of two integers in the_pair //Returns the sum of two integers in the_pair

Slide 17- 36

Template Functions with Template Functions with Template Class ParametersTemplate Class Parameters

Function add_up from a previous example Function add_up from a previous example can be made more general as a template can be made more general as a template function:function: template<class T> template<class T> T add_up(const Pair<T>& the_pair) T add_up(const Pair<T>& the_pair) //Precondition: operator + is defined //Precondition: operator + is defined

// for T// for T //Returns sum of the two values in //Returns sum of the two values in

// the_pair// the_pair

Slide 17- 37

The example in the following displays is a The example in the following displays is a class template whose objects are listsclass template whose objects are lists The lists can be lists of any typeThe lists can be lists of any type

The interface is found in the next two The interface is found in the next two slides.slides.The program is in the two slides after The program is in the two slides after those.those.The implementation is in the next three The implementation is in the next three slides.slides.

Program Example:Program Example:An Array ClassAn Array Class

Slide 17- 38

Slide 17- 39

Slide 17- 40

Slide 17- 41

Slide 17- 42

Slide 17- 43

Slide 17- 44

Slide 17- 45

typedef and Templatestypedef and TemplatesYou specialize a class template by giving a You specialize a class template by giving a type argument to the class name such as type argument to the class name such as Pair<int>Pair<int>

The specialized name, Pair<int>, is used The specialized name, Pair<int>, is used just like any class namejust like any class name

typedef and Templatestypedef and Templates

You can define a new class type name You can define a new class type name with the same meaning as the specialized with the same meaning as the specialized name:name:

typedef Class_Name<Type_Arg> typedef Class_Name<Type_Arg> New_Type_Name;New_Type_Name;For example: For example:

typedef Pair<int> PairOfInt;typedef Pair<int> PairOfInt; PairOfInt pair1, pair2; PairOfInt pair1, pair2;

Slide 17- 47

Section 17.2 ConclusionSection 17.2 Conclusion

Can youCan you

Give the definition for the member function Give the definition for the member function get_element for the class template Pair?get_element for the class template Pair?

Give the definition for the constructor with Give the definition for the constructor with zerozeroarguments for the template class Pair?arguments for the template class Pair?

Slide 17- 48

Chapter 17 -- EndChapter 17 -- End