CS210 Lab: Templates Postlab

Postlab Exercise:

There are three parts to this postlab exercise. In the first part, you will convert a integer linked list class into a linked list class template. The second part will test your understanding of class templates and function templates. The third part is a general programming question.

Part 1:

Given the following linked list class which works for integers, convert it into a class template:
Note: you will also have to convert ListElement to a class template.

class LinkedList;

class ListElement
    int datum;
    ListElement* next;
    ListElement (int const&, ListElement*);

    friend LinkedList;

class LinkedList
    ListElement* head;
    LinkedList ();
    ~LinkedList ();
    bool IsEmpty () const;
    int const& First () const;
    int const& Last () const;
    void Prepend (int const&);
    void Append (int const&);
    void Extract (int const&);
    void Print ();

Part 2:


A function or class template is a framework. The compiler must generate the details of the functions or classes through a process know as instantiating.

Through this process, actual types (or classes) are substituted in for "dummy" or placeholder types. In other words, the compiler generates different versions based on the specified type (or class).

Instantiation works a little different for classes than for functions.

Given the following function prototype and class outline:

function prototype:

template <class type> myfunc(type a, type b);

class outline:

template <class type>
class myarray
	type a[10];
		for (int i; i<10; i++)
Specify how to instantiate the following:
  1. myfunc for integers
  2. myarray for doubles
  3. myfunc for characters
  4. myarray for characters

Part 3:

You may have noticed that when you declare and initialize floating point numbers in a line like the following:
float x=3.12;
You may get a warning:
warning C4305: 'initializing' : truncation from 'double' to 'float'

For Answers, click here
Back to Template Lab click here

CS Dept Home Page
CS Dept Class Files
CS210 Class Files

Copyright: Department of Computer Science, University of Regina.