template < parameters > class ....{ ..... };
template < parameters > function { ..... }
template_name < actual_parameters > .....;
Not on final.
Not in Labs.
You may need them in your future career.... perhaps.
Are non-member template functions declared the same as member function?
Yes.... but no need for a
ClassName::before the generic function:
template<typename T> Type_returned name(arguments){body}
For example
template<class T> void swap(T&a, T&b){ T t=a; a=b; b=t; }
See
[ tswap.cpp ]
(note -- there is a version of swap in the std library so I don't use namespace std).
These days put helper classes and functions in the private part
of the helped class.
How does a class template differ from a class?
A class template is a rubber stamp that produces classes (instances)
as we need them. It describes an infinite set of possible
classes. A class describes only one class.
If a template is declared template<class T> can T be a simple data type?
Yes. I think so. I find it less confusing to write "template <typename T>"
instead.
What do we do with a definition and a header file if the header defines a template?
Keep the bodies inside the header.
Why does anybody ever put the bodies in a separate file?
(1) To hide the details of your clever coding and data from other programmer's
eyes. This means they can't take advantage of any tricks inside the functions.
All they can see (and abuse) are the headers in the '.h' file.
(2) You can precompile the bodies into a ".o" object file once. Then you don't have to wait for the compiler to recompile it every time you use it.
Note: if you do split body from header.... use a tool like "make" to
handle compilations.
Are there any predefined template classes in the standard library?
Yes. Hundreds. Including: vector, dequeue, list, ...... Even the <algorithm>s
are template functions!
We made a template in CS201.... and it was quite useful!
Cool!
How do you have different types in a single typename parameter?
Set up a object-oriented hierarchy and put pointers in the instance:
vector< Shape *> shapes;See [ 18.html ] next class.
. . . . . . . . . ( end of section CSci202 Computer Science II, Session 17, Template Classes) <<Contents | End>>
Laboratory on templates
[ lab09.html ]
Next -- Project 5 and Chapter 14.2
Project 5 (Ch 13.1..11) is due! Resubmit 4.
Topic (chapter 14, section 14.2)
Introduction to template functions
[ 18.html ]
Abbreviations