Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 5 OOP Course. 5. Templates Motivation A function for finding minimum value For floats we will need another function typeCan we parameterize this."— Presentation transcript:

1 Lecture 5 OOP Course

2 5. Templates

3 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) }

4 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

5 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

6 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); }

7 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

8 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)

9 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;

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

11 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..

12 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..

13 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

14 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

15 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

16 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..

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

18 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..

19 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..

20 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..

21 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

22 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

23 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

24 Example: Ordered list

25 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

26 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

27 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..

28 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

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

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

31 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..

32 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..

33 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


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

Similar presentations


Ads by Google