#ifndef Nodes_H #define Nodes_H /////////////////////////////////////////////////////////////////////////// // Nodes.h - demonstrate how to define a template node class // // ver 1.1 // // Language: Visual C++, 2008 // // Platform: Dell Precision T7400, Vista Ultimate, SP1 // // Application: CSE687 - Demo for Project #1, Spring 2009 // // Author: Jim Fawcett, Syracuse University, CST 4-187, // // (315) 443-3948, jfawcett@twcny.rr.com // /////////////////////////////////////////////////////////////////////////// /* * Module Operations: * ================== * Provides a template Node class that holds a finite number of pointers * to child nodes, and a visitation predicate. * * Build Process: * ============== * cl /D:TEST_NODES Nodes.cpp * * Maintenance History: * ==================== * ver 1.1 : 30 Jan 10 * - added virtual std::string ToString() method * - removed boolean mark, now use index of children for marking * - added empty virtual destructor * ver 1.0 : 23 Jan 09 * - first release */ #include #include #include namespace AbstractDataTypes { template class MNode { public: MNode(const T& t=0); virtual ~MNode() {} void add(MNode* pMNode); bool remove(MNode* pMNode); MNode* nextUnmarkedChild(); void clearMarks(); T& value(); virtual std::string ToString(); // Compiler generated copy and assignment are shallow. // That makes sense for a Node class. private: std::vector< MNode* > children; T t_; size_t visitIndex; }; //----< construct accepts value, can be used as void ctor >-------------- template inline MNode::MNode(const T& t=0) : t_(t), visitIndex(0) {}; //----< add child node >------------------------------------------------- template inline void MNode::add(MNode* pMNode) { children.push_back(pMNode); } //----< return instance of template type >------------------------------- template inline T& MNode::value() { return t_; } //----< remove child node - returns false on failure, else true >-------- template bool MNode::remove(MNode* pMNode) { std::vector< MNode* >::iterator iter = children.begin(); for(iter=children.begin(); iter!=children.end(); ++iter) { if(pMNode == *iter) { children.erase(iter); return true; } } return false; } //----< return pointer to next unvisited child or null >----------------- template MNode* MNode::nextUnmarkedChild() { if(children.size() == 0) return 0; if(visitIndex < children.size()) { return children[visitIndex++]; } return 0; } //----< "mark" all children as unvisited >------------------------------- template void MNode::clearMarks() { visitIndex = 0; } //----< return default string representation of template type >---------- // // This fails to compile if T instances can't be converted to std::string // template std::string MNode::ToString() { std::ostringstream temp; temp << "<" << t_ << ">"; return temp.str(); } } #endif