20-CS-122-001 Computer Science II Spring 2012
Class Template: Tricky Use of Display

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Lectures      Source     (Java doesn't do this - no Java version)

#include <iostream>
#include <stdio.h>
using namespace std;

template <class V, class X>
class Test {
   char *buffer;
   V *val;    // Class "V" expected to have method "value"
   X *object;
   char *(*disp) (X *);
   
 public:
   Test (V *v, char *(*d)(X *), X *x) { 
      val = v;
      buffer = new char[1024];
      disp = d; 
      object = x; 
   }

   void display () { 
      cout << "V: " << val->value() << "  X: " << disp(object) << "\n"; 
   }

   char *value () { 
      sprintf(buffer,"%s",(char *)val);
      return buffer; 
   }
};

// A function template - assumes class "T" has method "value"
template <class T>
char *display (T *object) {  return object->value();  }

// Class "Int" as before
class Int {
   int number;
   char *buffer;

 public:
   Int (int n) { number = n; buffer = new char[1024]; }

   char *value () { 
      sprintf(buffer,"%d",number);
      return buffer; 
   }
};

// Class "Float" as before
class Float {
   float number;
   char *buffer;

 public:
   Float (float n) { number = n; buffer = new char[1024]; }

   char *value () { 
      sprintf(buffer,"%f",number);
      return buffer; 
   }
};

// C++ Craziness - must use ...> > instead of ...>> below!!!!!
int main() {
   Test<Int,Int> *test = new Test<Int,Int>(new Int(23), display, new Int(45));
   test->display();

   Test<Float,Test<Int,Int> > *next 
      = new Test<Float,Test<Int,Int> >(new Float(33.1), display, test);

   next->display();
}

// Result:
//   V: 23  X: 45
//   V: 33.099998  X: