Templates - PowerPoint PPT Presentation

About This Presentation
Title:

Templates

Description:

What happens if we want to swap a double ? or a string? ... All these versions of Swap are 'isomorphic' // template code for Swap for arbitrary type T ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 33
Provided by: csHu
Category:
Tags: swap | templates

less

Transcript and Presenter's Notes

Title: Templates


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
  • Piece of code that will be regenerated with
    different arguments each time
  • templateltclass Tgt // 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
    intand compiles the code defined by it

7
Template Instantiation
  • Different instantiations of a template can be
    generated by the same program
  • See Swap.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)

9
Another Example
  • // Inefficient generic sort
  • templatelt class T gt
  • void
  • Sort( T begin, T end )
  • for( begin ! end begin )
  • for( T q begin1 q ! end q )
  • if( q lt begin )
  • Swap( q, begin )
  • See Sort.h, TestSort.cpp

10
More Complex Case
  • Suppose we want to avoid writing operator ! for
    new classes
  • template ltclass Tgt
  • 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 )
  • 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.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
  • templateltclass Tgt
  • class MyList
  • MyListltintgt intList // T int
  • MyListltstringgt stringList // T string

15
Class Templates
  • Code similar to usual code
  • Add templateltgt 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.h

16
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
  • MyListltintgt list
  • list.copy( array, 6 )
  • Alternative use a pointer to initial position
    and one to the position after the last
  • list.copy( array, array6 )
  • This form is more flexible (as we shall see)

17
Constructing a List
  • // Fancy copy from array
  • templatelt class T gt
  • MyListltTgtcopy( 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
  • Applies to all elements in begin,end-1
  • Common in C/C programs
  • Can we extend it to other containers?

19
Iterator
  • Object that behaves just like a pointer
  • Allows to iterate over elements of a container
  • Example
  • MyListltintgt L
  • MyListltintgtiterator i
  • for( i L.begin() i ! L.end() i )
  • cout ltlt " " ltlt i ltlt "\n"

20
Iterators
  • To emulate pointers, we need
  • copy constructor
  • operator (copy)
  • operator (compare)
  • operator (access value)
  • operator (increment)

21
MyListltTgt 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.h

22
Side Note operator
  • In C we can use in two forms
  • prefix notation x
  • increment x
  • fetch xs value
  • postfix notation x
  • fetch xs value
  • increment x
  • How can we implement both variants?

23
Operator
  • Prefix form
  • T Toperator()
  • Postfix form
  • T Toperator(int) // dummy argument!
  • Note different return types
  • See MyListWithIterators.h

24
Initializing a List
  • We now want to initialize a list from using parts
    of another list
  • Something like
  • templatelt class T gt
  • MyListltTgtcopy( iterator begin,
  • iterator end )
  • iterator p
  • for( p begin p ! end p )
  • pushBack(p)

25
Generic Constructor
  • The code for copying using
  • T
  • MyListltTgtiterator
  • are essentially identical
  • on purpose --- iterators mimic pointers
  • Can we write the code once?

26
Template within a template
  • template lt class T gt class MyList
  • templatelt class Iterator gt
  • copy( Iterator begin, Iterator end )
  • for( Iterator p begin p ! end p )
  • pushBack(p)

27
Copy Method
  • MyListltTgtcopy() can be instantiated with
    different types
  • pointer to T
  • MyListltTgtiterator
  • Iterators of other data structures that contain
    objects of type T

28
Template Variations
  • Can receive constant arguments
  • templatelt class T, int Size 1024gt
  • class Buffer
  • private
  • T m_valuesSize
  • Bufferltchargt Buff1
  • Bufferltchar,1024gt Buff2 // same as Buff1
  • Bufferltint, 256gt Buff3

29
Template and Types
  • Buffer is not a type
  • Bufferltchar,1024gt is a type
  • Bufferltchargt, bufferltchar,1024gt are two names for
    the same type
  • Bufferltchar,256gt is a different type

30
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

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

32
Things to read about
  • Standard Library
  • ltstringgt implementation of string
  • ltalgorithmgt - algorithms (sort, swap, etc.)
  • ltutilitygt - relational operators
Write a Comment
User Comments (0)
About PowerShow.com