[   ^ to index...   |   <-- previous   |   next -->   ]

Template classes

Template functions are neat enough, but the most compelling use of templates is in template classes. The syntax is similar to that for defining a template function:

template <class T> class ListNode { public: ListNode(T* init_elem, ListNode<T>* init_next) : element(init_elem), next(init_next) {} T * element; // Stores items externally ListNode<T> * next; // Note recursive template use }; template <class T> class LinkedList { public: LinkedList() { head = NULL; } void append(T* value); T* removeFront(); private: ListNode<T> * head; // Note use of previous template };

The "template" declaration must be repeated when defining member functions:

template <class T> void LinkedList<T>::append(T* value) { if (head == NULL) { head = new ListNode<T>(value, NULL); } else { ListNode<T> * cursor = head; while (cursor->next != NULL) cursor = cursor->next; cursor->next = new ListNode<T>(value, NULL); } }

Usage is as follows:

LinkedList<int> ilist; int *x = new int(1); ilist.append( x ); cout << *ilist.removeFront() << endl;

Class templates are never instantiated implicitly. With constructor overloading and other C++ features, implicit class template instantiation would be too confusing.

Download sample code...


Last modified: Mon Jul 31 21:18:42 PDT 2000