20-CS-122-001 Computer Science II Spring 2012
Class Template

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

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

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

// Template class.
// This class will be used as class "V"
template <class V, class X>
class Test {
   V *val;    // Objects of class "V" expected to have method "value"
   X *object;
   char *(*disp) (X *);
   
 public:
   Test (V *v, char *(*d)(X *), X *x) { val = v; disp = d; object = x; }

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

   char *value () { return "Test: no value"; }
};

// Template function - inputs objects are of class with method "value"
// returning "char *".
template <class T>
char *display (T *object) {  return object->value();  }

// This class will be used as "V" and "X"
class Int {
   int number;
   char *buffer;

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

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

// This class will be used as "X"
class Float {
   float number;
   char *buffer;

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

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

class A {
public:
   A () { }
};

void main() {
   Test<Int,Int> *test = new Test<Int,Int>(new Int(23), display, new Int(45));
   test->display();

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

// Result:
//  V: 23  X: 45
//  V: Test: no value  X: 33.099998