Understanding the C++ Templates
Learn how the templates work for various data types.
We'll cover the following...
The “empty stack” error in C++
When we attempt to pop an element from an empty stack without proper checking, we might face an error or exception called an “empty stack” error. The following code snippet gives us a more robust stack data structure where we remove all the elements and catch the Stack<>::pop(): empty stack exception message.
After we look at the output, we’ll see why we need to know how to create general template classes and generic methods. Here’s the output:
501
The stack is not empty.
500
The stack is not empty.
500
Exception: Stack<>::pop(): empty stack
-
Lines 9–46 The code above implements a generic stack class (
Stack<T>) using a vector to store elements. The stack supports the following operations:push(),pop(),top(), andempty(). -
Line 50: In the
main()function, astackIntegersnamed instance of theStack<int>class is created. -
Lines 53 and 54: Integer elements (
500and501...