CPSC 427: Object-Oriented Programming
Michael J. Fischer
Templates
Template overview Templates are instructions for generating code.
Are type-safe replacement for C macros.
Can be applied to functions or classes.
Allow for type variability.
Example:
template <class T>
class FlexArray { ... };
Later, can instantiate
class RandString : FlexArray<const char*> { ... };
and use
FlexArray<const char*>::put(store.put(s, len));
Template functions
Definition:
Use:
Specialization
Definition:
This overrides the template body for int arguments.
Template classes
Like functions, classes can be made into templates.
template <class T>
class FlexArray { ... };
makes FlexArray into a template class.
When instantiated, it can be used just like any other class.
For a flex array of ints, the name is FlexArray<int>.
No implicit instantiation, unlike functions.
Compilation issues
Remote (non-inline) template functions must be compiled and linked for each instantiation.
Two possible solutions:
Template parameters
Templates can have multiple parameters.
Example:
template<class T, int size> declares a template with two
parameters, a type parameter T and an int parameter size.
Template parameters can also have default values.
Used when parameter is omitted.
Example:
template<class T=int, int size=100> class A { ...
}.
A<double> instantiates A to type A<double, 100>.
A<50> instantiates A to type A<int, 50>.
Templatizing a class
Demo 22a-BarGraph-template results from templatizing Row and Cell classes in 13-BarGraph.
Template parameter T replaces uses of Item within Row.
Here is what was necessary to carry this out:
Using template classes
Demo 22b-Evaluate is a simple expression evaluator based on a
precedence parser.
It uses templates and derivation together by deriving a template class
Stack<T> from the template class FlexArray<T>, which is a simplified
version of vector<T>.
The precedence parser makes uses of two instantiations of Stack<T>: