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 ListNode { public: ListNode(T* init_elem, ListNode * init_next) : element(init_elem), next(init_next) {} T * element; // Stores items externally ListNode * next; // Note recursive template use }; template class LinkedList { public: LinkedList() { head = NULL; } void append(T* value); T* removeFront(); private: ListNode * head; // Note use of previous template }; The "template" declaration must be repeated when defining member functions:
template void LinkedList ::append(T* value) { if (head == NULL) { head = new ListNode (value, NULL); } else { ListNode * cursor = head; while (cursor->next != NULL) cursor = cursor->next; cursor->next = new ListNode (value, NULL); } } Usage is as follows:
LinkedList 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.