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
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*xlooks 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*3and 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+1which 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?
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