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

时间:2023-03-09 14:39:26
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&) = ;
}; template <typename T>
struct Visitor<T>
{
virtual void Visit(const T&) = ;
}; struct stA;
struct stB; struct Base
{
typedef Visitor<stA, stB> MyVisitor;
virtual void Accept(MyVisitor&) = ;
}; 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 = ;
Base* base = &a;
base->Accept(vis);
base = &b;
base->Accept(vis); getchar();
return ;
}