Implementing the visitor pattern using C++ Templates

前端 未结 3 584
猫巷女王i
猫巷女王i 2020-12-05 00:47

I\'ve been trying to reduce the amount of boilerplate in my code, by using C++ Templates to implement the visitor pattern. So far I\'ve come up with this:

cl         


        
3条回答
  •  鱼传尺愫
    2020-12-05 01:28

    Your BaseVisitor does nothing for you, other than allowing arbitrary visitees to delete the visitor. Instead, you want to have a base class for the visitor which provides all of the different accept functions that could be called on it, and for the Visitable to accept this visitor.

    To do this, you could use a type list to define the types the visitor can accept, have a base visitee class which takes the type list, and add the type list as a parameter to your visitee implementation.

    sketch of example:

    // assuming a typelist has typedefs first and second and a 
    // type 'empty' representing end of type list
    
    template
    class Visitor : public Visitor {
    public:
        // visitor has a visit function for each type in Types
        virtual void visit(typename Types::first& visitable) = 0;
    };
    
    template<> class Visitor { };
    
    template
    class Visitable{
        public:
        // base accepts a visitor which can visit any type in Types
        virtual void accept(Visitor& visitor) = 0;
    };
    
    template
    class VisitableImpl : public Visitable {
    public:
        // impl calls specific visit function 
        virtual void accept(Visitor& visitor) override {
            visitor.visit(static_cast(*this));
        }
    };
    

提交回复
热议问题