The purpose of this lab is to add exception handling and an index operator to a template class.
Log into Sleipnir and create a new directory for this lab. Download the
files
genericlist.cpp and
lab1main.cpp to that directory.
You can download these files using the wget
command or by
copying the whole file from your browser window and using the command
:set paste
in vim.
Even though two files are provided, this code does NOT use seperate
compilation. It uses the include
directive to "cut and paste"
genericlist.cpp into lab1main.cpp. You compile lab1main.cpp like any other
program with the command (NOTE: the code will NOT compile until you add the
index operator):
g++ -g -o lab1 lab1main.cpp
The genericlist.cpp file contains a template class that allocates a dynamic array based on the data passed to the constructor. Pay special attention to the syntax above the template class. This is required whenever you wish to have a friend function of a template class. In this case, the friend function is the output operator which prints all of the elements to the given output stream.
In the lab1main.cpp file, the pretty_print()
function wraps
around the output operator to create a nicer looking output. The double
version sets the precision to two decimal places while the template version
adds a tab before the output. These are global functions which take a
template class object. There is another global function,
run_tests()
, which creates the template objects and tests their
functionality. Finally in main()
, input arrays of various
datatypes are created and passed to run_tests()
to test the
template class.
bad_alloc
exception if it occurs and set the array pointer to
NULL and the size to 0.