记录一些利用变长模板等改善设计的技巧

本质上是利用变长模板解决参数个数的问题。

#pragma once
#include 
#include 
#include 
#include 
template 
class Creater
{
public:
	Creater() : iT(nullptr) {}
	~Creater() = default;
	template
	void createT(Args&&... args)
	{
		iT = new T(std::forward(args)...);
	}
private:
	std::unique_ptr iT;
};

template 
class CallbackHolders
{
public:
	CallbackHolders() = default;
	~CallbackHolders() = default;

	void addCallback(std::function aCallback)
	{
		iCallbacks.push_back(aCallback);
	}

	template
	void invoke(Args&&... args)
	{
		for (auto& callback : iCallbacks)
		{
			callback(std::forward(args)...);
		}
	}
private:
	std::vector> iCallbacks;
};


int main()
{
	CallbackHolders holders;
	holders.addCallback([](int a, int b)->void {std::cout << "a + b = " << a + b << std::endl;
	});

	holders.invoke(3, 4);
	
	CallbackHolders holders1;
	holders1.addCallback([](std::string a)->void {std::cout << a << std::endl; });
	holders1.invoke("aaa");

	return 0;
}

 

 

 

 

 

 

 

 

你可能感兴趣的:(C++)