C++ 委托妙用

重点:

1.利用观察者,注册需要处理的用户(Test)(右值处理方法也是妙处)

2.用户自身采用模板去调用观察者的类(方法甚妙)

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

class Test
{
public:
	Test() = default;
	~Test() = default;


	virtual void DoIt() = 0;


};

//每个A和B可以执行自己的判断逻辑
class TestA: public Test
{
public:
	TestA() = default;
	~TestA() = default;
	template<class T>
	TestA(T* t)
	{
		m_func = [t](const int& num)
		{
			t->GetData(num);
		};
	}
	void DoIt() override
	{
		m_func(10);
	}
protected:
	std::function<void(const int&)> m_func;
};

//每个A和B可以执行自己的判断逻辑
class TestB : public Test
{
public:
	TestB() = default;
	~TestB() = default;
	template<class T>
	TestB(T* t)
	{
		m_func = [t](const int& num, const int& num2)
		{
			t->GetData(num, num2);
		};
	}
	void DoIt() override
	{
		m_func(20,10);
	}
protected:
	std::function<void(const int&,const int&)> m_func;
};

class A
{
public:
	A() = default;
	~A() = default;
	//执行不同函数
	void GetData(const int& num)
	{
		std::cout << num * 2 << std::endl;
	}

	void GetData(const int& num, const int& t)
	{
		std::cout << num * t << std::endl;
	}

	//利用右值引用处理指针
	void AddTest(std::shared_ptr<Test>&& t)
	{
		m_test.emplace_back(std::forward<std::shared_ptr<Test>>(t));
	}

	void DoIt()
	{
		for (const auto&var: m_test)
		{
			var->DoIt();
		}
	}

public:
	void CreateTest();

private:
	std::vector<std::shared_ptr<Test>> m_test;
};

void A::CreateTest()
{
	auto testA = std::make_shared<TestA>(this);
	AddTest(testA);
	auto testB = std::make_shared<TestB>(this);
	AddTest(testB);
}

int main() {
	std::shared_ptr<A> a= std::make_shared<A>();
	a->CreateTest();
	a->DoIt();
	return 0;
}
相关推荐
【ql君】qlexcel3 分钟前
Notepad++ 复制宏、编辑宏的方法
开发语言·javascript·notepad++··宏编辑·宏复制
Zevalin爱灰灰12 分钟前
MATLAB GUI界面设计 第六章——常用库中的其它组件
开发语言·ui·matlab
冰糖猕猴桃20 分钟前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
wt_cs1 小时前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python
_WndProc1 小时前
【Python】Flask网页
开发语言·python·flask
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
DolphinDB1 小时前
如何在C++交易系统中集成高性能回测与模拟撮合
c++
能工智人小辰2 小时前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT2 小时前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
筏.k2 小时前
C++ 网络编程(14) asio多线程模型IOThreadPool
网络·c++·架构