Tom Kelliher, CS23
Apr. 16, 1997
Class Templates:
A mechanism which allows the designer to add a parameter to a class definition. This parameter is ordinarily used to allow the creation of, for example, list of any type from a single list class.
template <class T> class Array { private: T *data; // Pointer to the array. int size; // Size of the array. public: Array(int s); ~Array() { delete [] data; } int Set(const T val, int pos); int Get(T &val, int pos); int Size(void) { return size; } // Hopefully obvious. };
/********************************************************************** * Array<T>::Array(int s) * * Create an array of type T of size s. Terminate if creation not * possible. **********************************************************************/ template <class T> Array<T>::Array(int s) : size(s) { data = new T[s]; assert(data != NULL); } /********************************************************************** * Array<T>::Set(const T val, int pos) * * Set the pos'th element of the array to val. * Return 1 if pos is valid, otherwise return 0. **********************************************************************/ template <class T> int Array<T>::Set(const T val, int pos) { if (pos < 0 || pos >= size) return 0; data[pos] = val; return 1; } /********************************************************************** * Array<T>::Get(const T val, int pos) * * Store the value of the pos'th element of the array in val. * Return 1 if pos is valid, otherwise return 0. **********************************************************************/ template <class T> int Array<T>::Get(T &val, int pos) { if (pos < 0 || pos >= size) return 0; val = data[pos]; return 1; }
/********************************************************************** * main.cc * A small program to demonstrate the use of a template-based array * class. **********************************************************************/ #include <iostream.h> #pragma implementation #include "array.h" /********************************************************************** * main() **********************************************************************/ int main() { Array<int> a(5); // array of 5 ints. int i; Array<char*> b(2); // array of 2 char*'s. char *s; a.Set(12, 0); a.Set(35, 1); a.Get(i, 0); cout << i << endl; a.Get(i, 1); cout << i << endl; cout << "Size: " << a.Size() << endl; cout << "\n==========\n\n"; b.Set("Hello", 0); b.Set("World", 1); b.Get(s, 0); cout << s << endl; b.Get(s, 1); cout << s << endl; cout << "Size: " << b.Size() << endl; return 0; }
#pragma interface
#pragma implementation