Lecture 5 OOP Course. 5. Templates Motivation A function for finding minimum value For floats we will need another function typeCan we parameterize this.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Queue Overview Queue ADT Basic operations of queue
Reviews for Exam 1 Chapter 1-4 CSc 212 Data Structures, Sec FG CCNY, Fall 2010.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Reviews for Exam 1 Chapter 1-4 CS 211 Data Structures MHC, 2007.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Typical operations on data –Add data.
Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Templates. Class templates – why? Writing programs we often use abstract data types such as stack, queue or tree. Implementations of these types may be.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
 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.
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
 2006 Pearson Education, Inc. All rights reserved Templates.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Chapter 12 Classes and Abstraction
Pointer to an Object Can define a pointer to an object:
CS Data Structures Chapter 8 Lists Mehmet H Gunes
OOP-4-Templates, ListType
Lists The List ADT.
C Basics.
Templates.
Introduction to Classes
CMSC 202 Lesson 22 Templates I.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Constructors and Destructors
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
9-10 Classes: A Deeper Look.
Templates I CMSC 202.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Lists CMSC 202, Version 4/02.
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
9-10 Classes: A Deeper Look.
Presentation transcript:

Lecture 5 OOP Course

5. Templates

Motivation A function for finding minimum value For floats we will need another function typeCan we parameterize this function with a type? Generic –Towards Generic Programming templates –Like objects are generalized into classes, we would like to generalize classes and functions into templates int min(int a, int b){ return (a<b ? a : b) } float min(float a, float b){ return (a<b ? a : b) }

void swap(int& a, int& b){ int temp = a; a = b; b = temp; } void swap(char& a, char& b){ char temp = a; a = b; b = temp; } void swap(float& a, float& b){ float temp = a; a = b; b = temp; } void swap(short& a, short& b){ short temp = a; a = b; b = temp; } void swap(boolean& a, boolean& b){ boolean temp = a; a = b; b = temp; } void swap(double& a, double& b){ double temp = a; a = b; b = temp; } void swap(string& a, string& b){ string temp = a; a = b; b = temp; } void swap(Parrot& a, Parrot& b){ Parrot temp = a; a = b; b = temp; } void swap(Cat& a, Cat& b){ Cat temp = a; a = b; b = temp; } void swap(Elephant& a, Elephant& b){ Elephant temp = a; a = b; b = temp; } void swap(Snake& a, Snake& b){ Snake temp = a; a = b; b = temp; } void swap(Crocodile& a, Crocodile& b){ Crocodile temp = a; a = b; b = temp; } void swap(Eagle& a, Eagle& b){ Eagle temp = a; a = b; b = temp; } Motivation

Templates super macro mechanism templateC++ provides a super macro mechanism that is identified by the keyword template TemplatesMACRO functionsclassesTemplates can be thought of as MACROs for functions and classes, that need not be explicitly called by the programmer Templatescompiler pre-processorTemplates are controlled by the compiler (and not by the pre-processor) Templates argumentsTemplates arguments are either class-types or const-expressions of a fixed type Arguments that are passed to temple functions are checked for type-mismatch

Function Template Preserving the semantics of a function Automatically generatedAutomatically generated instance of a function, varying by type The programmer parameterizes all or a subset of the types in the interface invariantfunction instancesunique data typeThe function implementation remains invariant over a set of function instances, each handling a unique data type template Type min(Type a, Type b) { return ( a>b ? a : b); }

Function Temples Cont. TemplatecalssT Template TTT T min(T a, T b){ return (a<b ? a : b) } operator< should be defined for calss T Declaration int main() int { int a=3, b=4; char char c= ‘a’, d = ‘b’; cout << min(a,b); // o.k cout << min(c,d); // o.k cout << min(a,c); // Error!! return 0; Usage Defining additional function int min(int, int) Will prevent the compilation error

Function Temples Cont. each call generate an actual functionFor each call to a function template, the compiler will try to generate an actual function with the appropriate prototype OverloadingOverloading for function of the same name is done in this order: exact –Look for an exact match among non-template functions exact –Look for an exact match that can be generated from function template –Look for the best match non-template functions, using 1.Trivial conversion 2.Promotions (e.g. short to int) 3.Standard conversions (e.g. int to double) 4.User-defined conversions (e.g. double to complex)

Class Templates Class templatesClass templates are used to define generic classes actual classAn actual class is created only when an actual object defined, using the class template with actual parameters templeteclassintclass templete class Buffer; Bufferchar* Buffer buf_chrp; Bufferint Buffer buf_int;

Example: class Bag add add getOne getOne isEmpty isEmpty isFull isFull currentSize currentSize capacity capacity

Bags With and Without Templates // BagOfInt.h #define CAPACITY 50 class BagOfInt{ public: BagOfInt(unsigned int max_capacity=CAPACITY); ~BagOfInt( ); // cont’d.. // Bag.h (template class) #define CAPACITY 50 template template class Bag { public: Bag(unsigned int max_capacity=CAPACITY); ~Bag( ); // cont’d..

Bags With and Without Templates // …BagOfInt.h cont’d int bool add( int * value ); int int * getOne( ); bool isEmpty( ) const; bool isFull( ) const; unsigned int currentSize( ) const; unsigned int capacity( ) const; // cont’d.. // …Bag.h cont’d (template) Item bool add( Item * value ); Item Item * getOne( ); bool isEmpty( ) const; bool isFull( ) const; unsigned int currentSize( ) const; unsigned int capacity( ) const; // cont’d..

Bags With and Without Templates // …BagOfInt.h cont’d private: unsigned int m_size; unsigned int m_max_capacity; int int ** m_container; }; // end of BagOfInt.h // …Bag.h cont’d(template) private: unsigned int m_size; unsigned int m_max_capacity; Item Item ** m_container; }; #include "Bag.template" // end of Bag.h

Bags With and Without Templates Differences between.template,.cpp files: BagOfInt :: Bag :: –Occurrences of BagOfInt :: are replaced by Bag :: template –Member functions, constructors, destructor are preceded by template Bag~Bag –Constructors are Bag; destructor is ~Bag Assumption: Item is a class –See use of NULL in add, getOne

Bags With and Without Templates // BagOfInt.cpp #include “BagOfInt.h” #include // continued on next slide // Bag.template #include “Bag.h” #include // continued on next slide

Bags With and Without Templates BagOfInt :: BagOfInt(unsigned int max_capacity) { m_max_capacity = max_capacity; m_size = 0; int m_container = new int*[m_max_capacity]; srand( (unsigned int) time( NULL ) ); } // cont’d.. template template Bag :: Bag (unsigned int max_capacity) { m_max_capacity = max_capacity; m_size = 0; Item m_container = new Item*[m_max_capacity]; srand( (unsigned int) time( NULL ) ); } // cont’d..

Bags With and Without Templates BagOfInt :: ~BagOfInt( ) { delete [ ] m_container; } // cont’d.. template template Bag :: ~Bag( ) { delete [ ] m_container; } // cont’d..

Bags With and Without Templates int bool BagOfInt :: add(int* value) { if (isFull() || (value == NULL) ) return false; m_container[m_size] = value; m_size++; return true; } // cont’d.. template Item bool Bag :: add(Item * value) { if (isFull( ) || (value == NULL) ) return false; m_container[m_size] = value; m_size++; return true; } // cont’d..

Bags With and Without Templates int int * BagOfInt :: getOne( ) { if (isEmpty( )) return NULL; unsigned int index = (unsigned int)( rand() * m_size / (RAND_MAX+1)); int* value = m_container[index]; m_container[index] = m_container[m_size-1]; m_size--; return value; } // cont’d.. template template Item Item * Bag :: getOne( ) { if (isEmpty( )) return NULL; unsigned int index = (unsigned int)( rand( ) * m_size / (RAND_MAX+1)); Item Item* value = m_container[index]; m_container[index] = m_container[m_size-1]; m_size--; return value; } // cont’d..

Bags With and Without Templates bool BagOfInt :: isEmpty( ) const { return (m_size == 0); } bool BagOfInt :: isFull( ) const {return (m_size == m_max_capacity ); } // cont’d.. template template bool Bag :: isEmpty( ) const { return (m_size == 0); } template template bool Bag :: isFull( ) const {return (m_size == m_max_capacity); } // cont’d..

Bags With and Without Templates unsigned int BagOfInt :: currentSize( ) const { return m_size; } unsigned int BagOfInt :: capacity( ) const {return m_max_capacity; } // end of Bag_Ptr.cpp template template unsigned int Bag :: currentSize( ) const { return m_size; } template template unsigned int Bag :: capacity( ) const {return m_max_capacity;} // end of Bag.template

Instantiating Bag Objects Bag bag(40); bagint // locally allocated bag for 40 ptrs to int Bag *bagPtr = new Bag (60); bagint // bagPtr holds the address of a dynamically // allocated bag that stores up to 60 pointers to int Bag > x(25); bagsint // locally allocated. bag x can hold 25 pointers to // bags, each of which can hold pointers to int Bag > *y = new Bag > (30); bag bags // y holds the address of a dynamically allocated bag // that stores up to 30 pointers to bags of pointers // to int

Instantiating Bag Objects When Bag > *y = new Bag >(30); is first encountered: –First, the class Bag is instantiated –Then the class Bag > is instantiated –Then the object y is instantiated When Bag and Bag > are encountered subsequently, the classes already exist

Example: Ordered list

Operations on OrderedList OrderedListConstruct an empty ordered list of objects isEmptyDetermine whether or not the list is empty getLengthGet the current size of the list removeRemove value at a given position from the list retrieveGet the Item at a particular location in the list insert sorted order Add an object to the list in a sorted order findReturn the position of a particular object in the list List orderedList Assuming we already have the class List, orderedList will use List to store the elements in a sorted order

OrderedList.h #include “List.h” template class OrderedList { public: OrderedList(unsigned int capacity = MAX_LIST); // constructor for an empty ordered list that // can hold up to capacity items; default // size is defined in List.h ~OrderedList( ); // destructor bool isEmpty( ) const; // true if list is empty, false otherwise

OrderedList.h int getLength( ) const; // returns the current size of the list Item remove (unsigned int pos); // remove the value at location pos and return it // precondition: pos must be a legal list position Item retrieve (unsigned int pos) const; // return value at pos without modifying the list. // precondition: pos must be a legal list position // cont’d..

OrderedList.h void insert (Item item); // insert item at appropriate pos’n in list int find (Item item) const; // return pos’n of first occurrence of // item, or -1 if item isn’t found private: List m_container; // to hold the list of Items }; // end of header file

OrderedList.template #include template OrderedList :: OrderedList (unsigned int capacity ) : m_container(capacity) { } template OrderedList :: ~OrderedList ( ) { } // cont’d..

OrderedList.template template bool OrderedList :: isEmpty( ) const { return m_container.isEmpty( ); } template int OrderedList :: getLength( ) const { return m_container.getLength( ); } // cont’d..

OrderedList.template template Item OrderedList :: remove (unsigned int pos) { return m_container.remove(pos); } template Item OrderedList :: retrieve (unsigned int pos) const { return m_container.retrieve(pos); } // cont’d..

OrderedList.template template void OrderedList :: insert (Item item) { for ( int k = 1; k <= getLength( ); k++ ) if ( item < retrieve(k) ) break; m_container.insert( k, item ); } // cont’d..

OrderedList.template template int OrderedList :: find (Item item) const { for ( int k=1; k <= getLength( ); k++ ) if ( item == retrieve(k) ) return k; return –1; } // end of OrderedList implementation Next lecture: OrederedList we will see a better way to implement OrederedList, usingInheritance