CMPT 225 Lab 5: C++ Template Classes


Creating a Template

C++ allows a programmer to create templates that can be instantiated.  A template allows objects to be created that can store (or use) data of any type.

In this lab you will convert the int linked list class to a template class. Start by downloading the zipfile. It contains:

To convert the class to a template class you must:

  1. Put the entire class (the .h file class definition, and the .cpp file method implementations) in one .h file. For this lab, put the entire class into LinkedList.h
  2. Preface the template class definition and each template member function implementation with this line: template <class Type>
  3. The class qualifier (LinkedList::) that appears before a method name in each implementation, should be replaced by LinkedList<Type>::
  4. Whenever the type that the class contains (int in our case) is referred to it should be replaced with the word Type
For example here is the add method before and after these changes:
void LinkedList::add(int x){
	Node *p = new Node; //temporary node
	// Assign appropriate values to the new node
	p -> data = x;
	p -> next = head;
	// Make the head point to the new node
	head = p;	
}
and the "templated" version
template <class Type>
void LinkedList<Type>::add(Type x){
	Node *p = new Node; //temporary node
	// Assign appropriate values to the new node
	p -> data = x;
	p -> next = head;
	// Make the head point to the new node
	head = p;	
}
To use your linked list template class in a program you need to specify what type is to be stored:

Testing

Test your linked list template by writing a driver program in template_test.cpp that creates an int linked list and a string linked list, and uses each of the LinkedList methods at least once.

When you have done this, please show a TA your modified driver program and the results of running it to receive your 1 mark for this lab.




Back to the CMPT 225 homepage.