Implementing the visitor pattern using C++ Templates

前端 未结 3 580
猫巷女王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:42

    This can be done in C++11 using variadic templates. Continuing from Pete's answer:

    // Visitor template declaration
    template
    class Visitor;
    
    // specialization for single type    
    template
    class Visitor {
    public:
        virtual void visit(T & visitable) = 0;
    };
    
    // specialization for multiple types
    template
    class Visitor : public Visitor {
    public:
        // promote the function(s) from the base class
        using Visitor::visit;
    
        virtual void visit(T & visitable) = 0;
    };
    
    template
    class Visitable {
    public:
        virtual void accept(Visitor& visitor) = 0;
    };
    
    template
    class VisitableImpl : public Visitable {
    public:
        virtual void accept(Visitor& visitor) {
            visitor.visit(static_cast(*this));
        }
    };
    

    Subclasses of Visitable:

    class Mesh : public Object, public VisitableImpl {};
    class Text : public Object, public VisitableImpl {};
    

    A Visitor subclass:

    class Renderer : public Visitor {};
    

    It's not clear what the value_type of your Scene container is but you need to obtain a reference or pointer to Visitable on which to call accept:

    for(Scene::iterator it = scene.begin(); it != scene.end(); ++it) {
        Visitable& object = static_cast&>(*it);
        if(pre_visit(object)) {
            object.accept(*this);
            post_visit(object);
        }
    }
    

提交回复
热议问题