CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.

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.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
 2006 Pearson Education, Inc. All rights reserved Templates.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
 2006 Pearson Education, Inc. All rights reserved Generics.
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.
Data Structures Chapter 2 Stacks Andreas Savva. 2 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one.
Review of C++ Programming Part II Sheng-Fang Huang.
Object Oriented Data Structures
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
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.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Polymorphism, Template, Preprocessor Lecture 6 June 28, 2004.
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.
CIS 270—Application Development II Chapter 18-Generics.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Templates Lecture 10 March 23, 2004.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Standard Template Library Lecture 9 March 22, 2005.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
© 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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
Chapter 22 - C++ Templates Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
 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.
Click to edit Master text styles Stacks Data Structure.
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.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
Session 03 - Templates Outline 03.1Introduction 03.2Function Templates 03.3Overloading Template Functions 03.4Class Templates 03.5Class Templates and Non-type.
Pointers and Dynamic Arrays
Chapter 22 - C++ Templates
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.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Stacks CS-240 Dick Steflik.
template< class T > class Stack { public:
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Corresponds with Chapter 5
Presentation transcript:

CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu

Template Definition template template (tem’plət, tem’plāt) noun 1.In an application package, an overlay for the keyboard that identifies keys and key combinations. 2.In image processing, a pattern that can be used to identify or match a scanned image. 3.In spreadsheet programs, a predesigned spreadsheet that contains formulas, labels, and other elements. 4.In MS-DOS, a small portion of memory that holds the most recently typed MS-DOS command. 5.In word processing and desktop publishing programs, a predesigned document that contains formatting and, in many cases, generic text.

C/C++ Template Definition A single segment that performs identical operations on different data types. Based on the argument types in a function call, the compiler generates separate object-code functions to handle each type of calls appropriately. The code segment allows the programmer to specify an entire range of related/overloaded functions or classes; the former is known as template functions, the latter template classes. Examples: sort function template for an array allows array of any data type (int, float, etc.) to be sorted and stack class templeate allows operations of stack-of-int, stack-of- double, etc.

Syntax: function template definition Funnction template begins with template Ortempleate Or template The formal parameters (system or user defined) can be used to specify the types of arguments to the function, the return type of a function, and to declare variables within the function.

Example: a function template // Fig 12.2: fig12_02.cpp // Using template functions #include template void printArray( const T *array, const int count ) { for ( int i = 0; i < count; i++ ) cout << array[ i ] << " "; cout << endl; }

Example: a function template (continued) int main() { const int aCount = 5, bCount = 7, cCount = 6; int a[ aCount ] = { 1, 2, 3, 4, 5 }; double b[ bCount ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char c[ cCount ] = "HELLO"; // 6th position for null cout << "Array a contains:" << endl; printArray( a, aCount ); // integer template function // a is of int * type cout << "Array b contains:" << endl; printArray( b, bCount ); // double template function // b is of double * type cout << "Array c contains:" << endl; printArray( c, cCount ); // character template function // c is of char * type return 0; }

How the above template simplify the code Without using function template, the programmer must write the following overloaded functions: void printArray(const int *, const int); void printArray(const double *, const int); void printArray(const char *, const int);

Overloading template functions The function templates can be overloaded with different number or types of parameters (same function name). The compiler performs a matching process to determine what function to call when a function is invoked. (non-template functions first)

Class templates Class is defined generically; objects of the class are defined with information of specific data type. Example: stack (LIFO) operation is independent of data type; stack class can be defined generically without specifying the data type of the object to be pushed onto or poped from the stack.

Class template Example: stack Identical to conventional class definition except it is preceded by: template

Class template Example: stack // Fig. 12.3: tstack1.h // Class template Stack #ifndef TSTACK1_H #define TSTACK1_H #include template class Stack { public: Stack( int = 10 ); // default constructor (stack size 10) ~Stack() { delete [] stackPtr; } // destructor bool push( const T& ); // push an element onto the stack bool pop( T& ); // pop an element off the stack private: int size; // # of elements in the stack int top; // location of the top element T *stackPtr; // pointer to the stack bool isEmpty() const { return top == -1; } // utility bool isFull() const { return top == size - 1; } // functions };

Class template Example: stack (continued) // Constructor with default size 10 template Stack ::Stack( int s ) { size = s > 0 ? s : 10; top = -1; // Stack is initially empty stackPtr = new T[ size ]; // allocate space for elements } // Push an element onto the stack; return 1 if successful, 0 otherwise template bool Stack ::push( const T &pushValue ) { if ( !isFull() ) { stackPtr[ ++top ] = pushValue; // place item in Stack return true; // push successful } return false; // push unsuccessful }

Class template Example: stack (continued) // Pop an element off the stack template bool Stack ::pop( T &popValue ) { if ( !isEmpty() ) { popValue = stackPtr[ top-- ]; // remove item from Stack return true; // pop successful } return false; // pop unsuccessful } #endif

Class template Example: stack (continued) // Fig. 12.3: fig12_03.cpp // Test driver for Stack template #include #include "tstack1.h" int main() { Stack doubleStack( 5 ); double f = 1.1; cout << "Pushing elements onto doubleStack\n"; while ( doubleStack.push( f ) ) { // success true returned cout << f << ' '; f += 1.1; } cout << "\nStack is full. Cannot push " << f << "\n\nPopping elements from doubleStack\n"; while ( doubleStack.pop( f ) ) // success true returned cout << f << ' ';

Class template Example: stack (continued) cout << "\nStack is empty. Cannot pop\n"; Stack intStack; int i = 1; cout << "\nPushing elements onto intStack\n"; while ( intStack.push( i ) ) { // success true returned cout << i << ' '; ++i; } cout << "\nStack is full. Cannot push " << i << "\n\nPopping elements from intStack\n"; while ( intStack.pop( i ) ) // success true returned cout << i << ' '; cout << "\nStack is empty. Cannot pop\n"; return 0; }

Observation of the example In the main driver function, the code for doublestack and intstack operations are nearly identical, suggesting opportunity to use a function template, which is illustrated in the following example.

Example: passing a stack template object to a function template // Fig. 12.4: fig12_04.cpp // Test driver for Stack template. // Function main uses a function template to manipulate // objects of type Stack. #include #include "tstack1.h" // Function template to manipulate Stack template void testStack( Stack &theStack, // reference to the Stack T value, // initial value to be pushed T increment, // increment for subsequent values const char *stackName ) // name of the Stack object { cout << "\nPushing elements onto " << stackName << '\n'; while ( theStack.push( value ) ) { // success true returned cout << value << ' '; value += increment; }

Example: passing a stack template object to a function template (continued) cout << "\nStack is full. Cannot push " << value << "\n\nPopping elements from " << stackName << '\n'; while ( theStack.pop( value ) ) // success true returned cout << value << ' '; cout << "\nStack is empty. Cannot pop\n"; } int main() { Stack doubleStack( 5 ); Stack intStack; testStack( doubleStack, 1.1, 1.1, "doubleStack" ); testStack( intStack, 1, 1, "intStack" ); return 0; }

Programming assignment Chapter 12: page 664, problem 12.8