Search code examples
c++software-designcode-duplication

How avoid code duplication in visitor and const visitor base classes


I have 2 classes ConstVisitorBase and VisitorBase which contain some code to visit objects. for example:

struct Node
{
    enum class Type { ... };
    Type type;
}

class ConstVisitorBase
{
    public:
        virtual void VisitType1( Node const & node );
        ...

    private:
        void VisitNode( Node const & node )
        {
            switch( node.type )
            {
                case Node::Type::type1: VisitType1( node );
            }
            ...
        }
}

class VisitorBase
{
    public:
        virtual void VisitType1( Node & node );
        ...

    private:
        void VisitNode( Node & node )
        {
            switch( node.type )
            {
                case Node::Type::type1: VisitType1( node );
            }
            ...
        }
}

The code for the private method VisitNode is identical other than the const specifier.

Is there a way to avoid this duplication?
Even when there are multiple methods involved ( VisitNode calling EnterNode and LeaveNode )?


Solution

  • Since VisitType1 are public and the two classes are unrelated, you can use a template function:

    template<typename Visitor, typename T>
    void dispatch_visits(Visitor& visitor, T&& node){
        switch( node.type )
        {
            case Node::Type::type1: visitor.VisitType1( node );
        }
        ...
    }