ds lect 04 - templates data stru

27
Data Structures and Algorithms Introduction to C++ Templates (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel, and from The C++ Programming Language, 3 rd edition, by Bjarne Stroustrup)

Upload: air-university-multan

Post on 27-Jun-2015

59 views

Category:

Science


4 download

DESCRIPTION

...

TRANSCRIPT

Page 1: Ds   lect 04 - templates data stru

Data Structures and Algorithms

Introduction to C++ Templates

(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, from C: How to Program, 5th and 6th editions, by Deitel and Deitel, and from The C++ Programming Language, 3rd edition, by Bjarne Stroustrup)

Page 2: Ds   lect 04 - templates data stru

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

Page 3: Ds   lect 04 - templates data stru

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

Page 4: Ds   lect 04 - templates data stru

Example

Page 5: Ds   lect 04 - templates data stru

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.

Page 6: Ds   lect 04 - templates data stru

Example – Function Overloading

Page 7: Ds   lect 04 - templates data stru

Problem

What about the case when all of the overloaded functions have essentially the same code, but for different types

Not good style to write a bunch of nearly identical code

– Inefficient use of programmer time– Various instances can get out of sync with each

other– Some cases might be missed

Page 8: Ds   lect 04 - templates data stru

Solution – Approach 3: Function Templates

A more compact and convenient form of overloading. Identical program logic and operations for

each data type.

Page 9: Ds   lect 04 - templates data stru

Function Template•A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types.

Template <typename T> func() {…}

FunctionTemplate

Page 10: Ds   lect 04 - templates data stru

Function Template Written by programmer once

Essentially defines a whole family of overloaded functions

Begins with the template keyword

Contains a template parameter list of formal type and the

parameters for the function template are enclosed in angle

brackets (<>)

Formal type parameters Preceded by keyword typename or keyword class

Placeholders for fundamental types or user-defined types

Page 11: Ds   lect 04 - templates data stru
Page 12: Ds   lect 04 - templates data stru

Function Template Example 1 // Fig. 18.12: maximum.h

2 // Definition of function template maximum.

3

4 template < class T > // or template< typename T >

5 T maximum( T value1, T value2, T value3 )

6 {

7 T maximumValue = value1; // assume value1 is maximum

8

9 // determine whether value2 is greater than maximumValue

10 if ( value2 > maximumValue )

11 maximumValue = value2;

12

13 // determine whether value3 is greater than maximumValue

14 if ( value3 > maximumValue )

15 maximumValue = value3;

16

17 return maximumValue;

18 } // end function template maximum

Using formal type parameter T in place of data type

Page 13: Ds   lect 04 - templates data stru

Result Whole Family of Overloaded Functions

All with the “same” source code

All doing the same thing, but with different data types

Defined in one place

Common Programming Errors– Not placing keyword class or keyword typename before every formal

type parameter of a function template

– Writing < class S, T > instead of < class S, class T > ) is a

syntax error

Page 14: Ds   lect 04 - templates data stru

Function Template Specialization

Specialization: the automatic generation of a new “overloaded function” from the template as needed

– i.e., whenever a function template is called with a particular type

Example for function template max with type parameter T called with int arguments Compiler detects a max invocation in the program

code. int is substituted for T throughout the template

definition. This produces function-template specialization max<int>

Page 15: Ds   lect 04 - templates data stru

1 // Fig. 18.13: fig18_13.cpp

2 // Function template maximum test program.

3 #include <iostream>

4 using std::cout;

5 using std::cin;

6 using std::endl;

7

8 #include "maximum.h" // include definition of function template maximum 9

10 int main()

11 {

12 // demonstrate maximum with int values 13 int int1, int2, int3; 14

15 cout << "Input three integer values: "; 16 cin >> int1 >> int2 >> int3; 17

18 // invoke int version of maximum 19 cout << "The maximum integer value is: " 20 << maximum( int1, int2, int3 ); 21

22 // demonstrate maximum with double values 23 double double1, double2, double3; 24

25 cout << "\n\nInput three double values: "; 26 cin >> double1 >> double2 >> double3; 27

Invoking maximum with int arguments

Specialization Example

Compiler:– 1. Suspends what it was doing2. Generates a new overloaded

function from template maximumfor parameter type int

3. Compiles this new function4. Returns to this program and

compiles a call to new function.

Page 16: Ds   lect 04 - templates data stru

28 // invoke double version of maximum

29 cout << "The maximum double value is: "

30 << maximum( double1, double2, double3 ); 31

32 // demonstrate maximum with char values

33 char char1, char2, char3;

34

35 cout << "\n\nInput three characters: ";

36 cin >> char1 >> char2 >> char3;

37

38 // invoke char version of maximum

39 cout << "The maximum character value is: "

40 << maximum( char1, char2, char3 ) << endl; 41 return 0; // indicates successful termination

42 } // end main Input three integer values: 1 2 3 The maximum integer value is: 3 Input three double values: 3.3 2.2 1.1 The maximum double value is: 3.3 Input three characters: A C B The maximum character value is: C

Invoking maximum with double arguments

Invoking maximum with char arguments

Specialization Example (continued)

Compiler does same again, but forparameter type double

And again, but forparameter type char

Page 17: Ds   lect 04 - templates data stru

Specialization (continued)

Each time that the compiler encounters a use of maximum with a type that it has not seen before … it creates a new instance of the function maximum with new parameter types

With new mangled name!

Page 18: Ds   lect 04 - templates data stru

Function Templates Summary

Very important for Code readability Code reuse Good coding style Programmer efficiency

Foundation of other template features in C++

Page 19: Ds   lect 04 - templates data stru

Summary of Three Approaches

Naïve ApproachDifferent Function Definitions

Different Function Names

Function OverloadingDifferent Function Definitions

Same Function Name

Template FunctionsOne Function Definition (a function template)

Compiler Generates Individual Functions

Page 20: Ds   lect 04 - templates data stru

Questions?

Page 21: Ds   lect 04 - templates data stru

Class Templates Class-template definitions are preceded by a

header Such as template< typename T >

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 – e.g., template< typename T1, typename T2 >

Also known asParameterized Types

Page 22: Ds   lect 04 - templates data stru

Class Templates (continued)

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

Page 23: Ds   lect 04 - templates data stru

Example of a Class Template – Generic List ADTconst int MAX_LENGTH = 10;

template <class ItemType>

class GList

{

private:

int length;

ItemType *list;

public:

GList(); // Constructor

bool isEmpty() const;

bool isFull() const;

int length() const;

void insert(ItemType item );

void delete(ItemType item );

bool isPresent(ItemType item ) const;

void sort();

void print() const;

};

Template parameter

Page 24: Ds   lect 04 - templates data stru

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.

Page 25: Ds   lect 04 - templates data stru

Instantiating a Class Template

// Client code GList<int> list1;GList<float> list2;GList<string> 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

Page 26: Ds   lect 04 - templates data stru

Substitution Example

class GList_int{

private: int length; ItemType *list;Public:

void insert(ItemType item );void delete(ItemType item );bool isPresent(ItemType item ) const;

};

Page 27: Ds   lect 04 - templates data stru

Function Definitions for Members of a Template Class

template<class ItemType>

void GList<ItemType>::insert(ItemType item )

{

list[length] = item;

length++;

}

//after substitution of float

void GList<float>::insert(float item )

{

list[length] = item;

length++;

}