- (Instructor)Template classes,
are commonly used for
operating on containers.
This is template-class.cpp from chapter seven
of the exercise files.
This is a simple lasting first out stack.
There's a more complete version
in the standard template library.
I've created this simple version so we can see how it works.
The important thing to notice about this,
is that there's really no code here that cares
about what type the items on the stack are.
And so if we come down here,
you know I have my little exception class here
for generating exceptions.
And then here's the class itself,
it's called Stack.
And you notice that it's in a template,
so it has a template type name T so that capital T
represents the type of the items on the Stack.
And so here we have a stack pointer,
which is simply a pointer to the items on the stack,
and they'll get allocated in the constructor,
with the new operator,
but at this point when we're writing the code,
we actually do not care what that type is.
So we have our public interface,
we have the constructor and the explicit keyword here simply
means that this constructor cannot be used with implicit
conversions that this int S will always be an end.
And here we have our destructor,
which is very simple.
We simply delete the stack pointer.
We have a push function and a pop function.
Both of these return a reference
to the item pushed or popped.
And we have some utility functions here.
We can test if our stack isEmpty(),
if our stack isFull()
and int top and the bottom.
Our constructor is very simple,
we first check if the size
is in our range of acceptable values,
and then we allocate memory for the stack
with the new operator,
and we set the top of the stack.
Push simply adds an item to the stack and returns it,
and pop simply returns the top item on the stack
and decrements the stack pointer.
Very simple.
And none of this code cares at all,
about the type of the items on the stack.
And so here you notice we're going to try block here
because we have exceptions,
and here we allocate a stack of ints,
and down here we allocate a stack of standard strings.
And in each case,
we push five items onto the stack.
We have a stack size of five,
we report the size of the stack the top of the stack.
And then we report the top of the stack after
we've pushed these five items on,
and whether or not it's full,
and while it's not empty,
we pop them out and display them.
And it's as simple as that.
We do that both for the integers and for the strings.
And you notice when we build on run,
this code works exactly the same for both the integers,
and for the STL strings.
And it's exactly the same code.
So template classes are especially useful
for manipulating containers of items,
where the logic of the manipulation
is independent of the type.
That's why the C++ standard containers,
are written using templates.
For a more comprehensive discussion of templates,
please see the companion course,
C++ templates and the STL.