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

本文介绍了一个使用C++模板实现的访问者模式的例子。该模式允许在不修改现有类的前提下为一组类定义新的操作。通过具体示例展示了如何为不同的结构体类型(stA 和 stB)定义并应用统一的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

 

转载于:https://www.cnblogs.com/kaishan1990/p/5137948.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值