title: Visitor pattern for const and nonconst versions of a tree
body: <p>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:</p>
  
  <pre><code>class Visitor;
  class ConstVisitor;
  
  class Node {
  public:
    virtual void accept(Visitor&amp;) = 0;
    virtual void accept(ConstVisitor&amp;) const = 0;
  };
  
  class Leaf : public Node {
    virtual void accept(Visitor&amp; v)        {v.visitLeaf(*this);}
    virtual void accept(ConstVisitor&amp; cv)  {cv.visitLeaf(*this);}
  };
  
  class CompoundNode : public Node {
  public:
    vector&lt;Node*&gt; getChildren() const;
    virtual void accept(Visitor&amp; v)        {v.visitCompoundNode(*this);}
    virtual void accept(ConstVisitor&amp; cv)  {cv.visitCompoundNode(*this);}
  };
  
  class Visitor {
  protected:
    virtual void processNode(Node&amp; node) = 0;
  public:
    void visitLeaf(Leaf&amp; leaf) {
      processNode(leaf);
    }
    void visitCompoundNode(CompoundNode&amp; cNode) {
      processNode(cNode);
      auto children = cNode.getChildren();
      for (auto child : children)
        child-&gt;accept(this);
    }
  };
  
  class ConstVisitor {
  protected:
    virtual void processNode(Node const&amp; node) = 0;
  public:
    void visitLeaf(Leaf const&amp; leaf) {
      processNode(leaf);
    }
    void visitCompoundNode(CompoundNode const&amp; cNode) {
      processNode(cNode);
      auto children = cNode.getChildren();
      for (auto child : children)
        child-&gt;accept(this);
    }
  };
  </code></pre>
  
  <p>Concrete visitor classes inherit either from <code>Visitor</code> or from <code>ConstVisitor</code>, depending on whether their <code>processNode</code> method has to alter the nodes visited or not.</p>
  
  <p>You see, there is lots of code duplication between the two visitors, and since I will have to implement another traversal strategy, also for both const and nonconst nodes, I want to avoid that duplication. Are there any possibilities to extract the duplicate code, preferably without using <code>const_cast</code> all over the place?</p>