CS320 Lecture: Templates Last revised 10/1/99
Need: Handouts and Transparency: STACK1.H, .CC; STACK2.H, GENERIC_SEARCH
Transparency of Chi_Array declarations from Horstmann
Transparency of Smart pointers
Transparency of store.h fields, store.cc selected methods
STL manual
I. Motivation:
- ----------
A. There are certain data structures that are widely useful to serve as
containers for various kinds of information, which have a behavior of
their own that is independent of the kind of information they contain.
Ex: stacks - behaviors push, pop, top, isempty
queues - behaviors insert, remove, front, isempty
graphs - behaviors dfs, bfs, spanning tree etc.
B. When using a language like Pascal or C, if one needs such a structure
one either types it in specialized for the particular type of element,
or uses search and replace to modify a previously-created version -
sometimes more than once in the same program.
Ex: CS122 project 2 involves a stack of integers and a stack of char
C. C++ supports TEMPLATES - generic structures that can be instantiated
for specific data types as needed.
Example: STACK1.H, STACK1.CC
DEMO
Note: Instantiation of class in main program
Inlining of methods in header
Example: STACK2.H (main program same except for #include)
Note: Alternative for defining methods - but still in header
template < class T > prefix for method bodies
Name of class is Stack<T> in definitions, Stack<int> or
whatever in use.
D. Actually, the template facility of C++ has many applications in addition
to creation of generic container classes (though that's one of its
more important uses).
1. Generic algorithms - e.g. a generic array search algorithm that can be
parameterized by the type of the object being searched for.
TRANSPARENCY: GENERIC ARRAY SEARCH
2. Improved arrays: Standard C++ arrays suffer three weaknesses:
a. Lower bound must be 0
b. No checking for index out of range
c. Size must be established at time of creation
The disk that comes with your book contains a header and implementation
for an Array template that overcomes these limitations.
TRANSPARENCY - Excerpts from Chi_Array declaration.
3. "Smart pointers"
a. It is common in OO programs for objects to be created dynamically at
run time using operator new. (Not only explicitly by the program,
but also implicitly by various container classes.) Of course, once
a dynamic object is no longer needed, it should be destroyed using
operator delete to free up storage - otherwise "memory leakage"
occurs. This, however, is error-prone.
i. However, it is easy to miss a case where an object should be
deleted, resulting in memory leaks.
Example: Problem with Driver's License system I was testing -
program got slower and slower over time, due to virtual
memory thrashing
ii. On the other hand, if one deletes an object that still has live
references to it, then one gets dangling references and the
potential for all manner of storage corruption and hard to
find errors.
b. There are three ways to handle this issue:
i. Make the programmer responsible for recycling what he no longer
needs - doesn't work well and indeed sometimes can't work well.
(But this is the standard C++ solution)
ii. Automatic Garbage collection - approach used by Smalltalk, Ada,
and Java
iii. Reference counting - each object carries a reference count -
when it gets to 0, object is deleted. This requires:
- Whenever a pointer is set to the object, the reference count is
incremented.
- Whenever a pointer that was pointing to the object is moved or
destroyed, the reference count is decremented and tested for 0
TRANSPARENCY - OBJECT.H (adapted from work done on Prolog+)
...
II. Using Templates in C++
-- ----- --------- -- ---
A. C++ allows the creation of two kinds of templates:
1. Class templates - specify a generic class (often a container but
not necessarily) that can be instantiated to create actual classes.
Example:
template < class T >
class SomeClass
{
...
2. Function templates - specify a generic function that can be
instantiated for specific argument types to create actual functions.
Example:
template < class T >
int someFunction(T arg)
{
...
B. In both cases, the templates are instantiated automatically by the
compiler.
1. A class template is instantiated when a variable or type is created
using the generic class name
Example (given the above):
SomeClass < int > i;
...
typedef SomeClass < char > SomeCharClass;
The first declaration creates an new class (SomeClass < int >) in
which all occurrences of T in the template are replaced by int,
and creates one object of this class.
The second declaration creates a new class (which can be called
either SomeClass < char > or SomeCharClass), in which all occurrences
of T in the template are replaced by char. Objects of this class
can now be created using SomeCharClass as a class name.
2. A function template is instantiated when a call to the function
occurs with parameters of a specific type.
Example (given the above):
someFunction(42);
Creates a new function someFunction(int) in which all occurrences
of T are replaced by int, and calls this function.
3. In either case, it the same template is used more than once with
the same types of parameter in same compilation, it is instantiated
only once.
Example (given the above):
someFunction(42);
...
int i;
...
someFunction(i);
...
someFunction(2 * i);
...
Would create only one function, and call it three times.
(However, if these calls occured in three different compilations,
the template would be instantiated three times, creating three
local versions of the same function).
C. In either case, a template specification begins with the reserved word
template, followed by a list of formal parameters enclosed in angle
brackets, followed by the definition of the template.
1. Templates can have any number of parameters.
2. The parameters can be either types or values or objects.
Example:
template < int i, class T, Foo O >
Creates a template with three parameters: an integer, a data type,
and an object of class Foo. This template might be instantiated
by
< 42, char, myFoo >
3. Datatype parameters are specified by using the word class. They
can be either standard types or class types - the word class in
this context has a broad meaning.
D. A template specification is normally placed in a header file, but
must include the complete implementation of the template, since the
compiler must construct a custom implementation each time the
template is used.
TRANSPARENCIES: STACK1.H and STACK2.H again - note structure
III. The Standard Template Library
--- --- -------- -------- ------
A. One piece of the on-going ANSI standardization effort for C++ is the
development of a standard template library (STL) - based on work done by
Alexander Stepanov of Silicon Graphics and Meng Lee of Hewlett Packard.
Their work has been made freely available to the public - e.g. the
manual is copyrighted by Hewlett Packard but can be freely reproduced and
distributed
SHOW MANUAL
B. Basic structure:
1. Containers
Sequences
Vector
List
Deque (from which Stack, Queue can be derived)
Associative containers
Set
Multiset
Map
Multimap
2. Iterators - interface is the same regardless of container; basically
looks like a standard C++ pointer - e.g.
* - accesses current object
++ - advances to next object
-- - backs up to previous object (if supported)
+ n - advances to nth next object (if supported)
etc.
3. Algorithms - standard operations on containers using iterators - e.g.
foreach
find
count
search
...
4. Function objects - passed to algorithms to specify how certain
operations (e.g. comparison) are to be done
Example: When the map template is instantiated, a function object
that knows how to compare keys for relative order
(less than) must be specified. For key types that can be
compared using the < operator, the template less < class T >
can be used to create the appropriate function object.
5. Allocators - manage memory
6. Adaptors - adapt the behavior of other components of the library
Example: There are Stack and Queue adapters to turn a deque into
a stack or queue.
C. Uses of STL containers and iterators in project
TRANSPARENCIES: typedefs in copy.h, customer.h, latecharge.h,
rentable.h, reservation.h
use of the above in store.h, customer.h
store.cc:
"Print out Contents of database" option
add Customer option
Copyright ©1999 - Russell C. Bjork