Presentation is loading. Please wait.

Presentation is loading. Please wait.

. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }

Similar presentations


Presentation on theme: ". Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }"— Presentation transcript:

1 . Templates

2 Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }

3 Example…  What happens if we want to swap a double ? or a string ? For each one, we need different function: void Swap( double& a, double &b ) { double tmp = a; a = b; b = tmp; } void Swap( string& a, string &b ) { string tmp = a; a = b; b = tmp; }

4 Generic Programming All these versions of Swap are “isomorphic” // template code for Swap for arbitrary type T void Swap( T& a, T &b ) { T tmp = a; a = b; b = tmp; }  Can we somehow tell the compiler to use Swap with any type T ?

5 Templates The template keyword defines “templates” u Piece of code that will be regenerated with different arguments each time template // T is a “type argument” void Swap( T& a, T &b ) { T tmp = a; a = b; b = tmp; }

6 Template Instantiation int main() { int a = 2; int b = 3; Swap( a, b ); // requires Swap( int&, int& ) } u The compiler encounters Swap( int&, int& ) u It instantiates the template Swap with T = int and compiles the code defined by it

7 Template Instantiation u Different instantiations of a template can be generated by the same program u See Swap.cpp

8 Templates & Compilation u A template is a declaration u The compiler performs syntax checks only u When a template is instantiated with specific arguments, then the generated code is compiled Implications: u Template code has to be visible by the code that uses it (i.e., appear in.h file) u Compilation errors can occur only in a specific instance (see Swap.cpp)

9 Another Example… // Inefficient generic sort… template void Sort( T* begin, T* end ) { for( ; begin != end; begin++ ) for( T* q = begin+1; q != end; q++ ) if( *q < *begin ) Swap( *q, *begin ); } See [Sort.h, TestSort.cpp]

10 More Complex Case… u Suppose we want to avoid writing operator != for new classes template bool operator!= (T const& lhs, T const& rhs) { return !(lhs == rhs); } When is this template used?

11 More Complex Case… class MyClass { public: … bool operator==(MyClass const & rhs) const; … }; … int a, b; … if( a != b ) // uses built in operator!=(int,int) … MyClass x,y; if( x != y ) // uses template with T = MyClass …

12 When Templates are Used? When the compiler encounters … f( a, b ) … u Search for a function f() with matching type signature u If not found, search for a template function that can be instantiated with matching types

13 Generic Classes?  Suppose we implement a class StrList that maintains a list of strings  See StrList.h and StrList.cpp  The actual code for maintaining the list has nothing to do with the particulars of the string type u Can we have a generic implementation of lists?

14 Class Templates template class MyList { … }; … MyList intList; // T = int MyList stringList; // T = string

15 Class Templates Code similar to usual code: u Add template statement before each top-level construct u Use template argument as type in class definition u Implementation of methods, somewhat more complex syntax  See MyList.h TestMyList.h

16 Constructing a List u We want to initialize a list from an array u We can write a method that receives a pointer to the array, and a size argument int array[] = { 1, 2, 3, 4, 5, 6 }; MyList list; list.copy( array, 6 ); u Alternative: use a pointer to initial position and one to the position after the last list.copy( array, array+6 ); u This form is more flexible (as we shall see)

17 Constructing a List // Fancy copy from array template MyList ::copy( T const* begin, T const* end ) { T const* p; for( p = begin; p != end; p++ ) pushBack(*p); }

18 Pointer Paradigm Code like: T * p; for( p = begin; p != end; p++ ) { // Do something with *p … } u Applies to all elements in [begin,end-1] u Common in C/C++ programs u Can we extend it to other containers?

19 Iterator u Object that behaves just like a pointer u Allows to iterate over elements of a container Example: MyList L; … MyList ::iterator i; for( i = L.begin(); i != L.end(); i++ ) cout << " " << *i << "\n";

20 Iterators To emulate pointers, we need: u copy constructor u operator = (copy) u operator == (compare) u operator * (access value) u operator++ (increment)

21 MyList iterator u Keep a pointer to a node class iterator { … private: Node m_pointer; }; u Provide encapsulation, since through such an iterator we cannot change the structure of the list See MyListWithIterators.h

22 Side Note operator++ In C we can use ++ in two forms:  prefix notation ++x  increment x  fetch x ’s value  postfix notation x++  fetch x ’s value  increment x How can we implement both variants?

23 Operator++ u Prefix form: T& T::operator++(); u Postfix form T T::operator++(int); // dummy argument! u Note different return types See MyListWithIterators.h

24 Initializing a List u We now want to initialize a list from using parts of another list u Something like template MyList ::copy( iterator begin, iterator end ) { iterator p; for( p = begin; p != end; p++ ) pushBack(*p); }

25 Generic Constructor u The code for copying using  T*  MyList ::iterator are essentially identical  on purpose --- iterators mimic pointers Can we write the code once?

26 Template within a template template class MyList { … template copy( Iterator begin, Iterator end ) { for( Iterator p = begin; p != end; p++ ) pushBack(*p); } … };

27 Copy Method u MyList ::copy() can be instantiated with different types  pointer to T  MyList ::iterator  Iterators of other data structures that contain objects of type T

28 Template Variations u Can receive constant arguments template class Buffer { … private: T m_values[Size]; }; … Buffer Buff1; Buffer Buff2; // same as Buff1 Buffer Buff3;

29 Template and Types  Buffer is not a type  Buffer is a type  Buffer, buffer are two names for the same type  Buffer is a different type

30 Class Templates - Recap u Provides support for generic programming u Parameters are either types or constants. Default values can be specified u Depends only on the properties it uses from its parameter types u Resulting classes may be very efficient, but code size may be larger u Difficult to write, maintain and debug u Class template overloading is impossible

31 Summary u Alternative mechanism to polymorphism u Write & Debug concrete example (e.g., StringList) before generalizing to a template u Understand iterators and other “helper” classes u Foundation for C++ standard library (STL)

32 Things to read about Standard Library u – implementation of string u - algorithms (sort, swap, etc.) u - relational operators


Download ppt ". Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }"

Similar presentations


Ads by Google