CS210 Lab: Templates Prelab Answers


Postlab Answers:

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 Class Template
 
 class LinkedList;

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

       friend LinkedList;
 };

 
 class LinkedList
 {
       ListElement* head;
 public:
       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 ();
 };
 template <class T>
 class LinkedList;

 template <class T>
 class ListElement
 {
       T datum;
       ListElement* next;
       ListElement (T const&, ListElement*);

       friend LinkedList <T>;
 };

 template <class T>
 class LinkedList
 {
       ListElement<T>* head;
 public:
       LinkedList ();
       ~LinkedList ();
       bool IsEmpty () const;
       T const& First () const;
       T const& Last () const;
       void Prepend (T const&);
       void Append (T const&);
       void Extract (T const&);
       void Print ();
 };


Part 2:

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];
public:
	myarray()
	{
		for (int i; i<10; i++)
			a[i]
	}
}
Specify how to instantiate the following:
  a.  myfunc for integers myfunc(10,20) //or any other integers
  b.  myarray for doubles myarray<double> a;
  c.  myfunc for characters myfunc('A','B') //or any other characters
  d.  myarray for characters   myarray<char> a;

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'
This is because literal floating point constants (such as 3.12) are treated as type double.
A single precision is indicated by following the number with either a f or F (F is preferred).

To get rid of the warning and still use floating point, you can write:

float x=3.12F;
In total, there are three floating point types:
  1. float--single precision (one word) (end with F)
  2. double--double precision (two words)
  3. long double--extended precision (three or four words) (end with L)

Back to Exercise 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.