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;
}
相关推荐
肆忆_10 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星14 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc