Skip to main contentCal State San Bernardino / [CNS] / [Comp Sci Dept] / [R J Botting] >> [CSci202] >> 18
[Index] [Schedule] [Syllabi] [Text] [Labs] [Projects] [Resources] [Search] [Contact] [Grading]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Mon Jun 4 17:21:28 PDT 2007

Contents


    CSci202 Computer Science II, Session 18, Template Functions


      (previous): Template Classes [ 17.html ]

      Preparation

      Study this page and 14.2 and write down the questions, doubts, and surprises that you have on a piece of paper.

      Assigned Work Due

      Project 5+resubmit P4.

      Hand in your questions, doubts and surprises. With page numbers and name.

      Input

      1. Generic Functions

        Heterogeneous Containers

        1. This replaces section 14.3. It is based 14.3.2 only.
        2. This is a K.I.S.S. guide to putting many different types of objects in a container.
        3. Logically they should all share some properties: so derive each type from a common Base class.

          Snake, Lion, Bird, etc are special kinds of Animal, Zoos have Animals

        4. Make sure that all function in the base class are virtual.
        5. For example:
           		class Animal{ .... virtual void sound()=0; ... };
           		class Snake: public Animal{ ...};
           		class Lion: public Animal{ ...};
           		class Bird: public Animal{ ...};
           		class Dog: public Animal{ ...};
           		class Cat: public Animal{ ...};
           		class Cow: public Animal{ ...};

          Put pointers in the container, not objects:
           		typedef vector < Animal* > Zoo;// collections of pointers to Animal
          Giving a name to the vector saves typing...
           		Zoo zoo;
           		zoo.push_back( new Cow("Bossy", ...));

           		Dog barker ("Barker", ...);
           		zoo.push_back( & barker);
        6. Iterators also have a pointer parameter:
           		for( Zoo::iterator p = zoo.begin(); p!=zoo.end(); p++)
        7. Don't forget to dereference the iterator twice!
           			(*p)->sound();

        . . . . . . . . . ( end of section Heterogeneous Containers) <<Contents | End>>

        Demo -- The Zoo Again

        Simplest doesn't work: [ animal.cpp ] [ animal2.cpp ] [ animal3.cpp ] [ animal4.cpp ] [ animal5.cpp ] [ animal6.cpp ] [ animal7.cpp ]

        Key Rule

        As a rule..... store pointers to objects (not the objects) in containers (and arrays). If you copy them into a container -- they lose their identity. But a pointer is a record of that identity. You don't want a Cat to forget how to "Meow" just because you put it on a farm!

        This is just like passing objects by reference not by value:

         		void good(Animal & a);
        Uses the address, no copying, no extra space used in the function.

         		void  bad(Animal   a);
        Copies the data that fits (only), reserves space for a copy, ...

        [ animal6.cpp ]

      Questions

        What is the syntax of a function template

          A function template is declared like this
          template < typename T > R N ( A );

          or this
          template < class T > R N ( A );

          and defined like this
          template < typename T > R N ( A ){ B }

          or this
          template < class T > R N ( A ){ B }

          where
          T is any identifier, usually T, that is called the template parameter.
          R is a result type. It can be "void", T, or any other class or type name.
          A is a possibly empty list of arguments. One must have type T or T&...
          B is the body of the function.
          N is the function name. If the function is a member function for class C then it must have form

           		C::N
          or
           		C < T >:: N

        What is a function template?

        A function template defines a whole family of similar functions. They are created, by the C++ compiler, by replacing the template parameter T by the type of data used in the argument list.

        What is an instance of a function template?

        When a function template is called, the compiler generates a special instance that is a normal function. The parameter T above is removed in the body of the template function and replaced by an actual data type. All the functions and operators etc are also regenerated for you (if possible).

        When should you template a function?

        When it is easy to do. Typically you've got an algorithm to work with ints, chars, or doubles and realizze it is the same algorithm whatever data you give it....

        When can the '&' be used and when omitted?

        Use the '&' in the argument of a function to get pass by reference whenever an argument is an object rather than a simple data type like "int", "char", ... It'll usually run faster, save space, and allow the object to behave like itself inside the function.

        What about const references & ?

        Use these when a function needs to use an object but not change it.

        Does C have templates?

        No. It had a dangerous and more powerful tool for generating code called a macro A macro is created like this
         	#define N(A) B
        from then on any reference to N(XXX) is replaced by a copy of B with XXX replacing A. There are no rules about what B is and what XXX is. As a result macros are powerful and surprising.

        Does C have function objects?

        To some extent. Any function has a name. The name, by itself, indicates the address of the function and so behaves like the address of an object, that behaves like a function. And an object that behaves like a function is a function object. However, C could not define classes of similar function objects.

        Can you make functions in the std library into templates?

        They are already templates!

        In the book what is IT?

        IT is a template parameter that will be an iterator.

        How do you test a destructor?

        It is easy to see if a destructor compiles and runs clean, but I can't think of a way to see if it is recycling all the memory correctly.

        If it fails to delete something then it will have a "memory leak" and it can take weeks of running the program for these to show up.

        If it deletes the same piece of memory twice then this may or may not work depending on the platform. Some platforms ignore extra deletes, but others give you a segmentation fault.

        This question is a powerful argument against the argument that testing can uncover all the problems with code. It shows that you may need more difficult techniques involving mathematics and logic to find all the bugs.

        What is an adapter function?

        An adapter function is like an adapter plug. It lets you plug into the wrong shaped socket.... If an object x has an operator f and you need a similar function g then you may be able to find a ready made or home made adapter a such that
      1. a(x).g(z) is passed to
      2. x.f(z)

        We will ignore them in the final.

        What is in <functional>?

        Some advanced and abstract functions. These a functions that operate on other functions to produce functions. In mathematics for example differentiation converts on function ( x*x for example) into another (2*x for example). Similarly <functional> is full of operations that take functions as data.

        As a rule they lead to elegant code for things that can be coded by less elegant means. They are mainly used when working with the algorithms library. I'll not mention them in the final.... but I think one may be needed in a lab.

        Here is a quote from the draft C++ standard


          2 Using function objects together with function templates increases the expressive power of the library as well as making the resulting code much more efficient.

          3 [Example: If a C++ program wants to have a by-element addition of two vectors a and b containing double and put the result into a, it can do:

               transform(a.begin(), a.end(), b.begin(), a.begin(), plus<double>());
          --end example]

          4 [Example: To negate every element of a:

               transform(a.begin(), a.end(), a.begin(), negate<double>());
          The corresponding functions will inline the addition and the negation. --end example]

        Reference: [ lib.function.objects in lib-utilities ]

        How to prepare for the final?

        Restudy the labs, quizzzes, web site, and book...

      Exercises

      Depends on the questions!

      SETE

    . . . . . . . . . ( end of section CSci202 Computer Science II, Session 18, Template Functions) <<Contents | End>>

    Lab 09 Templates

    [ lab09.html ]

    Next (chapter 15) Miscellanea

    [ 19.html ]

    Abbreviations

  1. TBA::="To Be Announced", something I have to do.
  2. TBD::="To Be Done", something you have to do.
  3. Dia::="A free Open Source Diagramming tool for Linux, Windoze, etc. ".
  4. YAGNI::="You Ain't Gonna Need It".
  5. DRY::="Don't Repeat Yourself".

End