C++设计模式-Visitor访问者模式

#include <iostream>
#include <string>
#include <string.h>
#include <memory>
#include <thread>
#include <Windows.h>
#include <future>

using namespace std;

template <typename... Types>
struct Visitor;

template <typename T, typename... Types>
struct Visitor<T, Types...> : Visitor<Types...>
{
    using Visitor<Types...>::Visit;
    virtual void Visit(const T&) = 0;
};

template <typename T>
struct Visitor<T>
{
    virtual void Visit(const T&) = 0;
};

struct stA;
struct stB;

struct Base
{
    typedef Visitor<stA, stB> MyVisitor;
    virtual void Accept(MyVisitor&) = 0;
};

struct stA : Base
{
    double val;
    void Accept(Base::MyVisitor& v)
    {
        v.Visit(*this);
    }
};

struct stB : Base
{
    double val;
    void Accept(Base::MyVisitor& v)
    {
        v.Visit(*this);
    }
};

struct PrintVisitor : Base::MyVisitor
{
    void Visit(const stA& a)
    {
        cout << "from stA: " << a.val << endl;
    }

    void Visit(const stB& b)
    {
        cout << "from stB: " << b.val << endl;
    }
};
int main()
{
    PrintVisitor vis;
    stA a;
    a.val = 8.97;
    stB b;
    b.val = 8;
    Base* base = &a;
    base->Accept(vis);
    base = &b;
    base->Accept(vis);

    getchar();
    return 0;
}

 

posted @ 2016-01-17 22:18  略加思索的河马  阅读(412)  评论(0编辑  收藏  举报