UMBC CMSC 202 Computer Science II
Lab11: Templates
Objective
In this lab you will use a linked list to practice using Templates.
Assignment: Fix the Linked List Class
Your assignment is fix the List Class so that it works with Templates. The Node class is perfectly fine, serves an example of how to use Templates, and should not be changed.
The linked list provided is a linked list, but the data type of its nodes has been deleted. We don't know what type object we will be required to put in the Linked List so we need to use Templates. There is a dummy node, called m_head, that is always
present in the list. This node contains no data and is not actually
considered an element. It is simply there to provide as a placeholder.
Step 1: Get the files
Here are the files you need:
- List.h: the header file for the
List class.
- List.cpp: the implementation
file for the List class. All the functions have been implemented, but any references to templated data types have been removed or left out, you need to put them back in.
- Tester.cpp: a file with a main
function that tests the templated linked list with a few data types.. You will not need to change this file.
Step 2: Template the function calls in the .cpp file
This means placing the following line above each function call: template < class Item > this tells the compiler that any reference within the following function to Item is a reference to a class named Item.
Step 3: Template the class scope resolution
This means placing < Item > in between List and :: in any occurances of List::
this tells the compiler to call the templated version of the function with the provided template class type.
Step 4: Template the objects
This means placing < Item > after every Node or List used in the .cpp
this tells the compiler to use Lists and Nodes of type Item where item will be specified by the calling function.
Step 5: Include the .cpp at the bottom of the .h
This is normaly a very bad thing to do, but it is required for templates to function. The compiler compiles templated classes upon the instantiation of a templated object with a type.
Step 6: Make sure the .cpp does not include the .h
Step 7: Fix anything note as needing fixing in the source files
Step 8: Compile and Debug
-
To compile, use:
g++ -Wall -ansi Tester.cpp
-
Bugs? Try to figure it out yourself first. If that doesn't work, as the TA
for help.