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;
}
相关推荐
苕皮蓝牙土豆2 小时前
C++ map容器: 插入操作
开发语言·c++
顾子茵2 小时前
c++从入门到精通(六)--特殊工具与技术-完结篇
android·开发语言·c++
byte轻骑兵2 小时前
【Bluedroid】蓝牙HID DEVICE 报告发送与电源管理源码解析
c++·hid·bluedroid
孞㐑¥2 小时前
Linux之基础IO
linux·开发语言·c++·经验分享·笔记
瓦力wow2 小时前
c语言 写一个五子棋
c语言·c++·算法
hjjdebug3 小时前
c/c++数据类型转换.
c语言·c++·数据类型变换
熬夜学编程的小王3 小时前
【C++进阶篇】C++容器完全指南:掌握set和map的使用,提升编码效率
c++·set·map
花火QWQ3 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
superior tigre4 小时前
C++学习:六个月从基础到就业——C++20:协程(Coroutines)
c++·学习·c++20
superior tigre4 小时前
C++学习:六个月从基础到就业——C++20:概念(Concepts)
c++·学习·c++20