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;
}
相关推荐
一朵梨花压海棠go2 分钟前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
蒋星熠7 分钟前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
翻滚丷大头鱼31 分钟前
Java 集合Collection—List
java·开发语言
小欣加油33 分钟前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL44 分钟前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae1 小时前
C++ -- 模板
开发语言·c++·笔记·其他
胡耀超1 小时前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda
索迪迈科技1 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
Zz_waiting.2 小时前
Javaweb - 14.6 - Vue3 数据交互 Axios
开发语言·前端·javascript·vue·axios
萌新小码农‍2 小时前
Java分页 Element—UI
java·开发语言·ui