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;
}
相关推荐
邪修king2 小时前
Re:Linux 系统篇(十七):进程篇(六):环境变量深度解析|命令行参数、环境变量表、4 种获取方式与继承机制万字详解
linux·服务器·c++
一只小阿乐2 小时前
java 快速上手开发 2
java·开发语言·前端
张宇Joaquin2 小时前
灵渠测试工具-urma_perftest
java·开发语言
高彬2 小时前
SAP ECC6.0 对接 C# web Services服务
开发语言·前端·c#·sap
张小姐的猫3 小时前
【C++开发脚手架】 —— Jsoncpp上手
java·linux·开发语言·网络·c++·tcp/ip·udp
一晌小贪欢3 小时前
python-第20天:关键字参数与不定长参数
java·开发语言·前端·python·数据可视化·函数参数·python办公
小灰灰搞电子3 小时前
Rust+Slint 实现蜂巢菜单源码分享
开发语言·rust·蜂巢菜单.
我命由我123453 小时前
JS Mock(Mock 拦截请求的前提、Mock 使用、关闭 Mock)
开发语言·前端·javascript·前端框架·html·html5·js
OPEN-F3 小时前
C++并发编程:异步任务与线程池实战
开发语言·c++·算法
心中有你02143 小时前
Python爬虫实战:京东商品数据爬取+可视化分析
开发语言·爬虫·python