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;
}
相关推荐
z187461030033 分钟前
list(带头双向循环链表)
数据结构·c++·链表
升鲜宝供应链及收银系统源代码服务4 分钟前
升鲜宝生鲜配送供应链管理系统---PMS--商品品牌多语言存储与 Redis 缓存同步实现
java·开发语言·数据库·redis·缓存·开源·供应链系统
大佬,救命!!!6 分钟前
python实现象棋
开发语言·python·学习笔记·pygame·少儿编程·记录成长
棉猴7 分钟前
《pygame中Sprite类实现多帧动画》注-通过多张序列帧显示动画2-2
开发语言·python·游戏·游戏程序·pygame
练习时长一年15 分钟前
Spring AoP的切点匹配
java·开发语言
来荔枝一大筐1 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
霜绛1 小时前
C#知识补充(一)——ref和out、成员属性、万物之父和装箱拆箱、抽象类和抽象方法、接口
开发语言·笔记·学习·c#
报错小能手1 小时前
C++笔记——STL list
c++·笔记
T.Ree.1 小时前
cpp_list
开发语言·数据结构·c++·list
laocooon5238578861 小时前
C++ 图片加背景音乐的处理
开发语言·c++