Lab 9 - Template Classes

Due: 10:00am on Wednesday

The purpose of this assignment is to add an output operator to a template class and to see the difference between template functions and specific-instance functions for global functions that take a template class.

For this assignment, we will be using the following simple template class (use copy and paste to put this in a file on Sleipnir, be sure to set paste mode in vi):

template <class T>
class simpleClass 
{
  private:
    T myVar;

  public:
    simpleClass() : myVar() {}
    simpleClass(T elem) : myVar(elem) {}
    simpleClass<T>& operator=(const simpleClass<T> &source) { 
      myVar = source.myVar;
      return *this;
    } 
};   
Add the output operator to this class. Recall that for the output operator to work correctly, you have to follow the following steps:
  1. Declare the prototype for the class: template <class T> class simpleClass;
  2. Declare the prototype for the output operator: template <class T> ostream& operator<<(ostream&, const simpleClass<T>&);
  3. Add the friend declaration to the class definition, using the diamond symbol to indicate this is a template function that is a friend: friend ostream& operator<< <>(ostream&, const simpleClass<T>&);
  4. Define the body of the output operator.
Add two global functions that take a simpleClass object as a parameter. These functions will be similar to the printLabel functions discussed in class. The first global function will be a template function called void printTest which will take a single simpleClass object and print "The content of the object is: " before calling the output operator on the object. The second global function will also be called printTest but will specifically take the double instance of simpleClass. It will format the double for 3 decimal places of precision and print out "The double is: " before calling the output operator for the object.

Use the following main() function to test your code:

int main()
{
  simpleClass<int> intA, intB(5);
  simpleClass<double> doubleA;
  simpleClass<char> charA('a');

  int v1;
  double v2;
  char v3;

  printTest(intB);
  cout << "Enter an integer: ";
  cin >> v1;
  intA = v1;
  printTest(intA);

  cout << "Enter a double: ";
  cin >> v2;
  doubleA = v2;
  printTest(doubleA);

  printTest(charA);
  cout << "Enter a character: ";
  cin >> v3;
  charA = v3;
  printTest(charA);

  return 0;
}
Email me your completed code.