[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci202] / 10
[Text Version] [Syllabus] [Schedule] [Glossary] [Resources] [Grading] [Contact] [Question] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] <10> [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Labs: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Wed May 6 16:51:34 PDT 2009

Contents


    CSci202 Computer Science II, Session 10, Template Functions


      (previous): Polymorphism [ 09.html ]

      Preparation -- 14 Templates 756

    1. 14.1 Introduction 757
    2. 14.2 Function Templates 758
    3. 14.3 Overloading Function Templates 761
    4. 14.4 Class Templates 761
    5. 14.5 Nontype Parameters and Default Types for Class Templates 768
    6. 14.6 Notes on Templates and Inheritance 769
    7. 14.7 Notes on Templates and Friends 769
    8. 14.8 Notes on Templates and static Members 770
    9. 14.9 Wrap-Up 771

      Notes on Templates

      [ templates.html ]

      Templates in the UML

      [ uml1a.html#Templates ]

      Assigned Work Due -- one Question

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

      What is the difference between templates and vectors

      Vectors are data. Templates are program.

      However, the "vector" class in C++ is a special class template and this is why we write

       		vector<int> counters;
      to construct a collection of ints.

      It might be defined as

       		template<typename T> vector;
      inside the <vector> library. Actually it is more complex and has another parameter that few people ever use.

      What should you keep in mind when writing a template function


      1. You can use the template parameters/arguments as variables.
      2. You don't know what the actual types of the data is -- keep to simple overloaded operations.
      3. You are writing a function -- all the normal thinking is needed.

      What is the purpose of nontype parameters

      The commonest use of a nontype parameter is to give the (fixed) size of some data storage:
       	template <int size> class Buffer {..... char b[size]; ....};

      What is the difference between a function and a class template

      A function template describes a family of functions with the same name, different types of data, and the same computations.

      A class template defines a family of classes. For a given set of actual parameters you get the right kind of attributes and functions for the actual class. For example

       	template <typename Data, int size> class Buffer {..... Data b[size]; ....};
      describes character buffers
       			Buffer<char, 8>
      and Unicode buffers
       			Buffer<wchar, 8>
      and so on...

      Templates a preprogrammed actions does it help software react in new ways

      Templates are not that much help since they are done by the compiler.

      Polymorphism lets a program reconfigures itself as it runs!

      How do you call a template function

      Just like a normal function. Just make sure you supply data of the right types.

      Do all templates start with template

      Pretty much. Only caveat -- functions inside a template class as also templated.

      Do templates speed up the program or the programmer

      The programmer.

      Are template classes used for other things than stacks

      YES! vectors, lists, heaps, trees, queues, arrays, buffers, priority-queues, red-black trees, hash tables, deques, .....

      Can macros be used in C++

      Macros were a part of the C language. C++ inheritted them.

      Macros described

      Macros look like this
       	#define identifier replacement
       	#define identifier(arguments) replacement

      The compiler has several passes through the program in the first pass -- the pre-processor -- it handles all the "pre-processor directives" -- marked by a "#".

      It stores the definitions (#define). If it sees an identifier from the first kind of define it removes it and inserts the replacement text. It does this even if the result is rubbish or worse surprising.

      If the pre-processor sees an identifier from the second form and it is called like this

       		identifier(actualArguments)
      then it copies the replacement text, changes the arguments to the actualArguments, and puts the result in place of the call. It does this without any form of checking. The results may not compile. Worse the often do something quite unexpected when they compile.

      As an example

       	#define double(x)	2*x
      looks simple and OK. As an inline template function
       		inline template<typename T> double(T x) {return 2*x;}
      it works exactly as you expect.

      As a macro the following works

       		double(3)
      the preprocessor replaces it by
       		2*3
      and when run you get "6" as the answer.

      Now try

       		double("boo")
      which attempts to compile
       		2*"boo"
      which fails to compile.

      Now suppose that you have

       		double(1+1)
      which generates the code
       		2*1+1
      which has value 3, rather than 4.

      As a result, wise macro programmers learn to write

       	#define double(x)	2*(x)

      But.... macros still generate surprising (dangerous) results.

       	#define max(x,y)	((x)<(y)?(x):(y))
      which works well even with
       		max(1+1, 2+2)
      which becomes
       		((1+1)<(2+2)?(1+1):(2+2))
      and produces 4, as expected.

      But if we have

       		int i=1;
      what does
       		max(i++,i++)
      do?

      Answer, it becomes,

       		((i++)<(i++)?(i++):(i++))
      and, this changes the value of i 3 times to become 4, and I'm not sure what it returns.

      And this is just the beginning with the confusions you can experience by using macros.

      They are not part of CSCI202. You can find them in an appendix of the text..... if you need them to work on old code.

      Templates vs Macros -- just say no to macros

      These days use a template!

      How are overloading and templates related

      what are some of the similarities and difference between overloading and templates?

    10. Overloading::="One name, different data".

      First, writing a template function creates a lot of new functions that all overload each other -- they all have the same name and different types of data.

      Next a templated function may overload previous one.

      C++ uses a variation of the algorithm for resolving overloading to find the template that matches the given function call.

      Can you overload a template

      Templates are always overloaded..... an you can (in theory) have a mixture of templates and plain functions with the same name and different data. But I think the compiler may get confused. Worse so might you,

      When are templates useful

      You need to understand them because the C++ Library of functions and classes use templates a lot. So you use/call them many times in any program -- and probably don't even notice it.

      You write a new ones less often. Mainly in quizzes and finals:-) However when you realizes that you have an idea for a function that could be used with all types of data and would have the same code you might as well write a template function.


      (DRY): Don't repeat yourself! If you ever find you have written the same function with different data, then you should have written it once, using a template instead.

      Template classes chiefly appear as data structures -- collections of items all of the same type. For example vector. Or a safe array. Again the standard C++ library the "STL" has a dozen of these ready to use.... more in classes 18 and 19. You can also create new ones ... but I'd suggest taking CSCI330 before you do this.

      What is the difference between class templates and class template specializations

      A specialization happens when you substitute the actual parameters into the class template. It generates a special class that fits that particular given data.

      Templates and Polymorphism --- are they complementary

      Yes. They come from two different developments in computer languages.

      One is handled by the compiler. The other at run time.

      One relies on a class hierarchy, the other does not.

      One needs a pointer and the other does not.

      If so can you give an example on the board

      Probably not.

      In what kinds of situations would you combine templates and polymorphism

      I think that this is how the iostream family of classes work.

      But in practice I can't think of an example of combining them.

      Memory used by templates -- can it be ignored

      Since templates don't usually consume more memory than separate overloaded functions, is the fear of a template consuming more memory still something to look out for?

      No. Use them without fear of wasting memory. You'd end up using the same amount of machine code by coding each special version of the function or class by hand.

      Stacks -- Last In First Out -- LIFO

      The book uses a stack, which it describes as a data structure where the last items input would be the first items retrieved, can you give an example of a stack being used?

      Demo in class.

      Lab later will show a classic use of a stack to evaluate expressions.

      Examples of templated classes

      [ Array.cc ] [ arith_float_collection.h ] [ tstack.cc ] [ vector.cc ] [ vector.h ] [ gin_stack.h ] [ gtin_stack.cpp ]

      Exercises

      Depends on the questions!

      Write a template function that returns the maximum of two things of the same type.

      Write a template function that returns the minimum of two things of the same type.

      Write a template function that swaps the values of two variables.

      Answer: [ 10templates.cpp ]

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

    Next -- Streams

    [ 11.html ]

    Next Project -- next week

    Abbreviations

  1. Algorithm::=A precise description of a series of steps to attain a goal, [ Algorithm ] (Wikipedia).
  2. class::="A description of a set of similar objects that have similar data plus the functions needed to manipulate the data".
  3. Data_Structure::=A small data base.
  4. Function::programming=A selfcontained and named piece of program that knows how to do something.
  5. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular and free C++ compiler.
  6. KDE::="Kommon Desktop Environment".
  7. object::="A little bit of knowledge -- some data and some know how", and instance of a class".
  8. OOP::="Object-Oriented Programming", Current paradigm for programming.
  9. Semantics::=Rules determining the meaning of correct statements in a language.
  10. SP::="Structured Programming", a previous paradigm for programming.
  11. STL::="The standard C++ library of classes and functions" -- also called the "Standard Template Library" because many of the classes and functions will work with any kind of data.
  12. Syntax::=The rules determining the correctness and structure of statements in a language, grammar.
  13. Q::software="A program I wrote to make software easier to develop",
  14. TBA::="To Be Announced", something I should do.
  15. TBD::="To Be Done", something you have to do.
  16. UML::="Unified Modeling Language".
  17. void::C++Keyword="Indicates a function that has no return".

End