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 different type such as double and string ? For each one, we need different function, code duplication a known bug recipe! 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” 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&) } The compiler encounters swap(int&, int&) It instantiates the template swap with T = int and compiles the code defined by it. Same as: swap (a,b);

7 Template Instantiation Different instantiations of a template can be generated by the same program. Swap example swap.cppswap.cpp

8 Templates & Compilation A template is a declaration. The compiler performs syntax checks only. When a template is instantiated with specific arguments, then the generated code is compiled Implications: Template code has to be visible by the code that uses it (i.e., appear in.h file). Compilation errors can occur only in a specific instance (see swap.cpp).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]Sort.hTestSort.cpp

10 More Complex Case… 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? Resolution When the compiler encounters … f( a, b ) … Search for a function f() with matching type signature. 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.cppStrList.h StrList.cpp The actual code for maintaining the list has nothing to do with the particulars of the string type 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: Add template statement before each top-level construct. Use template argument as type in class definition. Implementation of methods, somewhat more complex syntax. –See MyList.h TestMyList.hMyList.h TestMyList.h

16 Iterators

17 Constructing a List We want to initialize a list from an array. 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 ); Alternative: use a pointer to initial position and one to the position after the last list.copy( array, array+6 ); This form is more flexible (as we shall see)

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

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

20 Iterator Object that behaves just like a pointer. 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";

21 Iterators To emulate pointers, we need: copy constructor for function call. operator = for assignments. operator == comparing two pointers. operator * for accessing a value operator++ for pointer arithmetic.

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

23 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?

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

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

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

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

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

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

30 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

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

32 Summary Use templates to express algorithms that apply to many argument types. Use template to express containers. Alternative mechanism to polymorphism. Write & Debug concrete example before generalizing to a template Understand iterators and other “helper” classes Foundation for C++ standard library (STL)

33 Things to read about Standard Library – implementation of string - algorithms (sort, swap, etc.) - 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