Templates by alllona

VIEWS: 102 PAGES: 4

									                      Templates
 Templates provide us with a way to reuse code
    without templates: the implementations of two classes, one
     for a list of integers and one for a list of doubles, would be
     identical but for the types of the contents.
    with templates: the type becomes a parameter, so there is no
     code duplication
 C++ provides
    function templates
    class templates




                                                                      1
              Function templates
 The definition and declaration are preceded by the line
                template <class T>

   OR           template <typename T>

 T is a type parameter.


 The compiler will generate a different function definition for each
   type for which you use the template.

 The function is called as usual.



                                                                        2
             Function templates
 Example:

 template <class T>              Use:
 void swap (T& a, T& b) {         int x = 10, y = 20;
      T temp;                     char c = ‘i’, d = ‘j’;
      temp = a;                   swap(x, y);
      a = b;                      swap(c, d);
      b = temp;
 }                               must be same type
   IMPORTANT!
   = must be a valid operation
   for objects of type T                                   3
                Class templates
 The syntax is similar to that for function templates:
    Precede the definition with
                template <class T>
   Specify the type when you create a new object.
   Most compilers do not allow separate compilation of
    template classes. Place the declaration and
    implementation in one file.
   It is possible to have more than one type parameter:
                template <class T1, class T2>
   Careful: Not all types may work with a template
   See ~b11/labs/Templates for examples we did in
    class.
                                                           4

								
To top