// File: genlist4.h // // A generic list class using templates // Version 2: use templates // Version 3: return TYPE values using a reference parameter // add iterator class // Version 4: remove() returns the number of items removed // throws exceptions #ifndef _genlist_h #define _genlist_h #include #include "errors.h" // Forward class declaration: says Iterator is a template class // template class Iterator ; // not Iterator // TYPE must support // assignment operator // copy constructor // comparison operators: < <= == >= > != // I/O operator: << // template class ListCell{ public: ListCell *next ; // next cell on the list TYPE data ; // data stored in this cell ListCell() : next(NULL) {} // constructors ListCell(const TYPE& t) : next(NULL), data(t) {} void *operator new(size_t) ; // Memory Allocation void *operator new[](size_t) ; void operator delete(void *) ; void operator delete[](void *) ; } ; template class GenList { friend class Iterator ; public: GenList() ; // constructor ~GenList() ; // destructor GenList(GenList&) ; GenList& operator=(const GenList&) ; void append(const TYPE&) ; // Add item to end of list void prepend(const TYPE&) ; // Add item to front of list int chop(TYPE&) ; // Remove & get first item void print() const ; // print items to stdout int remove(const TYPE&) ; // Remove every item with given key inline int begin(TYPE&) const ; // get item at the front inline int end(TYPE&) const ; // get item at the end inline int length() const ; // Return number of items in list void *operator new(size_t) ; // Memory Allocation void *operator new[](size_t) ; void operator delete(void *) ; void operator delete[](void *) ; protected: ListCell dummy ; // dummy ListCell (not pointer!) ListCell *last ; // last item in the list int len ; // number of items in the list enum {clean = 0, dirty} ; int cache_status ; // clean or dirty } ; template class Iterator { public: Iterator(GenList&) ; // constructor needs a GenList int next(TYPE&) ; // get data in next node int set(const TYPE&) ; // replace this node's data void *operator new(size_t) ; // Memory Allocation void *operator new[](size_t) ; void operator delete(void *) ; void operator delete[](void *) ; private: GenList& L ; // remember the list ListCell *cache_ptr ; // previous position in list bool good ; // all ok? } ; //======================================================================== // GenList inline functions // template inline int GenList::begin(TYPE& result) const { if (dummy.next == NULL) return false ; result = dummy.next->data ; // uses TYPE assignment return true ; } template inline int GenList::end(TYPE& result) const { if (last == &dummy) return false ; result = last->data ; // uses TYPE assignment return true ; } template inline int GenList::length() const { return len ; } #endif