KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am stuck with a code duplication issue, regarding the visitor pattern for a tree. The current situation is as follows: I have a tree, consisting of two different node classes, i.e. leafs and non-leafs. In addition I have two visitor base classes that look very alike except that one visits const trees and the other non-const trees. The actual actions the concrete visitors have to do are independent of the node's concrete types. I'll give a short example: class Visitor; class ConstVisitor; class Node { public: virtual void accept(Visitor&) = 0; virtual void accept(ConstVisitor&) const = 0; }; class Leaf : public Node { virtual void accept(Visitor& v) {v.visitLeaf(*this);} virtual void accept(ConstVisitor& cv) {cv.visitLeaf(*this);} }; class CompoundNode : public Node { public: vector<Node*> getChildren() const; virtual void accept(Visitor& v) {v.visitCompoundNode(*this);} virtual void accept(ConstVisitor& cv) {cv.visitCompoundNode(*this);} }; class Visitor { protected: virtual void processNode(Node& node) = 0; public: void visitLeaf(Leaf& leaf) { processNode(leaf); } void visitCompoundNode(CompoundNode& cNode) { processNode(cNode); auto children = cNode.getChildren(); for (auto child : children) child->accept(this); } }; class ConstVisitor { protected: virtual void processNode(Node const& node) = 0; public: void visitLeaf(Leaf const& leaf) { processNode(leaf); } void visitCompoundNode(CompoundNode const& cNode) { processNode(cNode); auto children = cNode.getChildren(); for (auto child : children) child->accept(this); } }; Concrete visitor classes inherit either from Visitor or from ConstVisitor , depending on whether their processNode method has to alter the nodes visited or not. You see, there is lots of code duplication betwee
Tags (comma-separated)
Save Edits
Cancel