//==================================================================== // TSimpleList Pluf CSC 221 2/3/2009 // Just a simple example of a template class, includes overloads // I hope it works... (it sould at least compile) //==================================================================== #ifndef TSIMPLELIST_H #define TSIMPLELIST_H #include using namespace std; //== to use a template friend function in a template class, must declare == template class TSimpleList; template ostream& operator<<(ostream& out, const TSimpleList& l); template class TSimpleList { public: TSimpleList() { n_ = 0; } TSimpleList(const TSimpleList& l); bool isFull() const { return n_ >= maxSize_; } bool add(T value); bool remove(T& value); TSimpleList& operator=(const TSimpleList& l); //== yeah, the following is a little crazy looking... == friend ostream& operator<<<>(ostream& out, const TSimpleList& l); private: enum{maxSize_ = 10}; // maximum number of items T list_[maxSize_]; // list of items int n_; // number of items }; template TSimpleList::TSimpleList(const TSimpleList& l) { n_ = l.n_; for(int i = 0; i < l.n_; i++) list_[i] = l.list_[i]; } template bool TSimpleList::add(T value) { if(n_ < maxSize_) { list_[n_] = value; n_++; return true; } return false; } template bool TSimpleList::remove(T& value) { if(n_ > 0) { n_--; value = list_[n_]; return true; } return false; } template TSimpleList& TSimpleList::operator=(const TSimpleList& l) { if(this != &list_) { n_ = l.n_; for(int i = 0; i < l.n_; i++) list_[i] = l.list_[i]; } return *this; } template ostream& operator<<(ostream& out, const TSimpleList& l) { if(l.n_ > 0) { int i = 0; out << '['; for(i = 0; i < l.n_ - 1; i++) out << l.list_[i] << ", "; out << l.list_[i] << ']'; } else out << "empty list"; return out; } #endif