Acyclic Visitor C++

此生再无相见时 提交于 2021-01-29 04:13:05

问题


I'm reading the book by Alexandrescu, and I've run into the Acyclic Visitor pattern. I think that it's possible to get rid of the macross that calls AcceptImpl method of the BaseVisitable class. Could you tell me, whether the following implementation bellow conforms the standard?

class BaseVisitor
{
public:
    virtual ~BaseVisitor() {}
};

template <class SpecificVisitable>
class SpecificVisitor
{
public:
    virtual void Visit(SpecificVisitable& t) = 0;

protected:
    ~SpecificVisitor() {}
};

template <class SpecificVisitable>
class BaseVisitable
{
public:
    void Accept(BaseVisitor& visitor)
    {
        SpecificVisitor<SpecificVisitable>& specificVisitor = dynamic_cast<SpecificVisitor<SpecificVisitable>&>(visitor);
        specificVisitor.Visit(static_cast<SpecificVisitable&>(*this));
    }
protected:
    ~BaseVisitable() {}
};

class A : public BaseVisitable<A>
{
public:
    void PrintA() { std::cout << "A\n"; }
};

class B : public BaseVisitable<B>
{
public:
    void PrintB() { std::cout << "B\n"; }
};

class PrintVisitor final:
    public BaseVisitor,
    public SpecificVisitor<A>,
    public SpecificVisitor<B>
{
public:
    virtual void Visit(A& a) override
    {
        a.PrintA();
    }

    virtual void Visit(B& b) override
    {
        b.PrintB();
    }
};

int main()
{
    A a;
    B b;

    PrintVisitor visitor;
    a.Accept(visitor);
    b.Accept(visitor);
}

来源:https://stackoverflow.com/questions/42575593/acyclic-visitor-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!