c++——委托

c++有委托吗? 没有!也完全没必要,根本就不需要。因为有更好的方式。编译器也不需要,对编译器来说也是一种浪费。所以这个实现还有必要吗? 有! 不然,怎么让你划水,混日子水文章呢。

C#中委托就是C++中的函数指针的一种。语法写起来又沙雕,又特么另类。当时我看到这个函数后面跟->指向,.* 这种东西时。。什么沙雕!!

auto fun(int a, char b)-> int; //表示返回int类型  

指定返回的类型 仅此而已。这种东西被人写出来。。。有用吗? 有用。 但,真不一定会用到。

下面是官方解释:

那么 委托中,会用到吗? 会。

这是一段开源委托:我不解释了,懂得可能一看就懂,不懂就慢慢懂。



#include <mutex>
#include <list>
#include <vector>
#include <memory>


template<typename>
class Delegate;

namespace DelegateImpl
{
template <typename TReturnType, typename... TArgs>
struct Invoker
{
	using ReturnType = std::vector<TReturnType>;

	public:
		static ReturnType Invoke(Delegate<TReturnType(TArgs...)> &delegate, TArgs... params)
		{
			std::lock_guard<std::mutex> lock(delegate.mMutex);
			ReturnType returnValues;

			for (const auto &functionPtr : delegate.mFunctionList)
			{
				returnValues.push_back((*functionPtr)(params...));
			}

			return returnValues;
		}
};

template <typename... TArgs>
struct Invoker<void, TArgs...>
{
	using ReturnType = void;

	public:
		static void Invoke(Delegate<void(TArgs...)> &delegate, TArgs... params)
		{
			std::lock_guard<std::mutex> lock(delegate.mMutex);

			for (const auto &functionPtr : delegate.mFunctionList)
			{
				(*functionPtr)(params...);
			}
		}
};
}

template<typename TReturnType, typename... TArgs>
class Delegate<TReturnType(TArgs...)>
{
	using Invoker = DelegateImpl::Invoker<TReturnType, TArgs...>;
	using functionType = std::function<TReturnType(TArgs...)>;

	friend Invoker;

	public:
		Delegate() {}
		~Delegate() {}

		Delegate(const Delegate&) = delete;
		const Delegate& operator =(const Delegate&) = delete;

		Delegate& Connect(const functionType &function)
		{
			std::lock_guard<std::mutex> lock(this->mMutex);

			this->mFunctionList.push_back(std::make_shared<functionType>(function));

			return *this;
		}

		Delegate& Remove(const functionType &function)
		{
			std::lock_guard<std::mutex> lock(this->mMutex);

			this->mFunctionList.remove_if([&](std::shared_ptr<functionType> &functionPtr)
			{
				return Hash(function) == Hash(*functionPtr);
			});

			return *this;
		}

		inline typename Invoker::ReturnType Invoke(TArgs... args)
		{
			return Invoker::Invoke(*this, args...);
		}

		Delegate& Clear()
		{
			std::lock_guard<std::mutex> lock(this->mMutex);

			this->mFunctionList.clear();

			return *this;
		}

		inline Delegate& operator +=(const functionType &function)
		{
			return Connect(function);
		}

		inline Delegate& operator -=(const functionType &function)
		{
			return Remove(function);
		}

		inline typename Invoker::ReturnType operator ()(TArgs... args)
		{
			return Invoker::Invoke(*this, args...);
		} 

	private:
		std::mutex mMutex;
		std::list<std::shared_ptr<functionType>> mFunctionList;

		inline constexpr size_t Hash(const functionType &function) const
		{
			return function.target_type().hash_code();
		}
};

猜你喜欢

转载自blog.csdn.net/qq_36912885/article/details/124379803