c++封装类似c#Lazy--延迟求值





前言:
延迟求值:有些时候我们将任务打包好,然后并不直接执行,然后对这列任务包进行调度。
-
其实在c++中延迟求值,最常用的方式就是使用生成器(functor), 即std::function来实现,std::package_task内部原理也一样,lambda表达式的原理
也是这样的。这个和c#中的Lazy的特性,和python中的闭包类似。道理一样。
-
--关于延迟求值得应用:
	如你封装一个线程池,然后可以通过向线程池中投递延迟求值封装的可调用对象来进行处理任何任务。-->百度搜索c++线程池很多实现。
直接上个源码吧:
	#ifndef LAZY_GDL_H
	#define LAZY_GDL_H
	
	#include
	#include
	#include
	#include
	namespace gdl {
	
		template
		struct Lazy {
	
			Lazy() = default;
	
			//延迟求值封装, 但这里的lambda表达式参数传递如何实现完美转发呢?lambda闭包参数为引用,很多时候会出事儿
			template
			Lazy(Func&& _func, Args&& ...args) {
				m_func = [&_func, &args...]{ return _func(args...); };
			}
	
			T& loadValue() {
				if (!m_value) {
					m_value = m_func();
				}
				return *m_value;
			}
	
			bool isValueCreated() {
				return m_value.has_value();
			}
			
		private:
			std::function m_func;
			std::optional m_value;
		};
	
		template
		gdl::Lazy::type>
			lazy(Func&& _func, Args&& ...args)
		{
			
			return gdl::Lazy::type>(std::forward(_func), std::forward(args)...);
		}
	
	
	
	}
	
	
	
	#endif

你可能感兴趣的:(c/c++,project)