13,【设计模式】代理

代理

代理

代理的本质是函数指针

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

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

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

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

advanced.h

cpp 复制代码
#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

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;
}
相关推荐
乌萨奇也要立志学C++41 分钟前
【C++详解】STL-list模拟实现(深度剖析list迭代器,类模板未实例化取嵌套类型问题)
c++·list
闻缺陷则喜何志丹1 小时前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
序属秋秋秋2 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
十秒耿直拆包选手10 小时前
Qt:主窗体(QMainwindow)初始化注意事项
c++·qt
霖0011 小时前
C++学习笔记三
运维·开发语言·c++·笔记·学习·fpga开发
mit6.82412 小时前
[shad-PS4] Vulkan渲染器 | 着色器_重新编译器 | SPIR-V 格式
c++·游戏引擎·ps4
tan77º13 小时前
【Linux网络编程】Socket - TCP
linux·网络·c++·tcp/ip
Mike_Zhang14 小时前
C++使用WinHTTP访问http/https服务
c++
CHANG_THE_WORLD14 小时前
「macOS 系统字体收集器 (C++17 实现)」
开发语言·c++·macos
GiraKoo14 小时前
【GiraKoo】Breakpad 崩溃分析系统
c++