当前位置: 首页 > news >正文

13,【设计模式】代理

代理

  • 代理
  • 支持任意参数的简单代理实现

代理

代理的本质是函数指针

代理分为单播,多播,动态多播(ue4中提出的)

单播:在网络通信中,单播是一种一对一的通信方式
多播:在网络通信中,多播是一种一对多的通信方式

支持任意参数的简单代理实现

advanced.h

#pragma once
#include <iostream>
#include <type_traits>
using namespace std;//工厂
template<class T, class ...ParamTypes>
T* CreateObject(ParamTypes &&...Param)
{return new T(std::forward<ParamTypes>(Param)...);
}//void(*Funcation)(int a, int b, int c);//最简单的代理(支持多参数代理)
template<class TObjectType,class TReturn,typename...ParamTypes>//对象类型,返回值,可变参数
class FDelegate
{
public:FDelegate(TObjectType* InObject, TReturn(TObjectType::* InFuncation)(ParamTypes...))//使用代理时需要传一个对象,因为通过对象调用:Object(InObject)//把对象进行初始化, Funcation(InFuncation)//函数指针初始化{}TReturn operator()(ParamTypes&&...Params)//重载操作符{//通过当前对象调用函数指针return (Object->*Funcation)(std::forward<ParamTypes>(Params)...);//完美转换,之后把参数传递}
private:TObjectType *Object;TReturn (TObjectType::* Funcation)(ParamTypes...);//声明一个函数指针,通过TObjectType::* Funcation指针调用ParamTypes...任意参
};//工厂
template<class TObjectType,class TReturn,typename...ParamTypes>
FDelegate<TObjectType, TReturn, ParamTypes...>CreateDelegate(TObjectType* InObject, TReturn(TObjectType::* InFuncation)(ParamTypes...))
{return FDelegate<TObjectType, TReturn, ParamTypes...>(InObject, InFuncation);//拷贝是指针的拷贝,内容不会拷贝,如果想拷贝内容需要进行深拷贝
}

学习.cpp

#include <iostream>
#include"advanced.h"struct FTestA
{};struct FTestB
{FTestB(int a, int b){}int print(int a, int b){printf("%i %i", a, b);return a + b;}
};int main()
{FTestA* p = CreateObject<FTestA>();FTestB* p2 = CreateObject<FTestB>(1,2);auto NewFunction = CreateDelegate(p2, &FTestB::print);int a = NewFunction(1, 2);cout << "\n" << a << endl;return 0;
}
http://www.lryc.cn/news/137810.html

相关文章:

  • 基于IDEA使用maven创建hibernate项目
  • 使用Termux在安卓手机上搭建Hexo博客网站,并发布到公网访问
  • 宝塔 杀死 java服务 netstat -tlnp | grep :7003 kill 2205698
  • Python3 数据类型转换
  • Cookie 和 Session 的工作流程
  • AutoSAR配置与实践(基础篇)3.6 BSW的WatchDog功能
  • 运维高级第6次作业
  • MongoDB使用GridFS存储大数据(Java)
  • 内网穿透实战应用-windwos10系统搭建我的世界服务器,内网穿透实现联机游戏Minecraft
  • pytorch基于ray和accelerate实现多GPU数据并行的模型加速训练
  • [蓝帽杯 2022 初赛]domainhacker
  • 在 Pytorch 中使用 TensorBoard
  • Grafana Dashboard 备份方案
  • opencv-疲劳检测-眨眼检测
  • 2023-08-24力扣每日一题
  • 蚂蚁数科持续发力PaaS领域,SOFAStack布局全栈软件供应链安全产品
  • Java后端开发面试题——消息中间篇
  • C++ Windows API IsDebuggerPresent的作用
  • 【JVM 内存结构 | 程序计数器】
  • 华为云Stack的学习(一)
  • 人类反馈强化学习RLHF;微软应用商店推出AI摘要功能
  • day1:前端缓存问题
  • 学习网络编程No.4【socket编程实战】
  • HarmonyOS学习路之方舟开发框架—学习ArkTS语言(状态管理 四)
  • arcgis--坐标系
  • LFS学习系列 第5章. 编译交叉工具链(1)
  • 网络互联与互联网 - TCP 协议详解
  • 开源在线图片设计器,支持PSD解析、AI抠图等,基于Puppeteer生成图片
  • 在Linux系统上安装和配置Redis数据库,无需公网IP即可实现远程连接的详细解析
  • 跨平台图表:ChartDirector for .NET 7.1 Crack