/////////////////////////////////////////////////////////// // MT2Q1alt.h - more direct use of functor than in MT2Q1 // - Here, instead of graph class, used simpler // node class to illustrate idea #include template class node; template struct IFunc { enum OpType { vertexOp, edgeOp }; typedef void(IFunc::*callback)(typename T t); virtual void operator()(T t, OpType ot)=0; }; template class node { public: node(size_t number, T t=0) : nodeNum_(number), value_(t), visited_(false), pFunc_(0) {} ~node() { // Can't delete children unless you are sure they were created on heap // for(size_t i=0; i* pNode) { children_.push_back(pNode); } bool& visited() { return visited_; } size_t size() { return children_.size(); } node* getNextUnmarkedChild() { for(size_t i=0; ivisited()) return children_[i]; return 0; } void doNodeOp() { if(pFunc_) (*pFunc_)(this, IFunc*>::vertexOp); } void doEdgeOp() { if(pFunc_) (*pFunc_)(this, IFunc*>::edgeOp); } void Register(IFunc*>* pFunc) { pFunc_ = pFunc; } private: size_t nodeNum_; T value_; std::vector children_; bool visited_; IFunc*>* pFunc_; }; template void DFS(node* pNode, IFunc*>& f) { static int lev = 1; pNode->visited() = true; pNode->doNodeOp(); for(size_t i=0; isize(); ++i) { node* pChild = pNode->getNextUnmarkedChild(); if(pChild) { pChild->doEdgeOp(); DFS(pChild,f); } } --lev; }