博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 实现then,lambda链式调用
阅读量:3577 次
发布时间:2019-05-20

本文共 2382 字,大约阅读时间需要 7 分钟。

lambda 链式调用

C++11支持lambda和function,在一些延迟计算的场景下,这个链式调用的需求更加强烈。链式调用的目的是,将多个函数按照前一个的输出作为下一个的输入串起来,然后推迟到某个时刻再计算。C++中链式调用比较少见,因为实现比较复杂。

template
class Task;template
class Task
{
public: Task(std::function
&& f) : m_fn(std::move(f)){
std::cout << "move construct func name : "<<__func__<< std::endl;} Task(std::function
& f) : m_fn(f){
std::cout <<"construct func name : "<< __func__<< std::endl;} R run(Args&& ... args){
std::cout <<"exec function,func name : "<<__func__<< std::endl; return m_fn(std::forward
(args)...); //perfect } // continue exec template
auto then(F && f)->Task
::type(Args...)>{ std::cout <<"then -> "<
<< std::endl;i++; using return_type = typename std::result_of
::type; //get F return type auto func = std::move(m_fn); return Task
([func,f](Args&& ...args){ return f(func(std::forward
(args)...)); }); } private: std::function
m_fn;};void TestTask(){ Task
task([](int i){ std::cout <<"init :"<
<< std::endl;return i;}); std::string str = "join in lambda then : "; auto res = task.then([&str](int i){ str += "then 1\t";std::cout <<"first:"<<< std::endl;return i + 1;}) .then([&str](int i){ str += "then 2\t";std::cout <<"second:"<<
(n)<<"tuple string : "<
<1>(n)<< std::endl; return std::make_tuple(std::get<0>(n) + 4,"then exec ecnd"); }).run(1); std::cout <<"result tuple value : "<
<0>(res)<<" result tuple string : "<< std::get<1>(res)<< " result string : "<
<
(f);}void testFuture(){ std::cout <<"at testFuture func thread : "<
<< std::endl; typedef std::future
A; typedef std::result_of
::type B; static_assert(std::is_same
::value,"not equal"); Task
::type(int)> task(fu); auto t = task.then([](auto o){ std::cout <<"wait value ..."<< std::endl; std::cout <<"at first then func thread : "<
<< std::endl; auto ii = o.get() + 100; auto f = std::async([](int i){ std::cout <<"new value :"<
<<" .."<< std::endl; std::cout <<"]async in thread : "<
<< std::endl; //std::chrono::milliseconds dre(i * 1000); //std::this_thread::sleep_for(dre); return i * i; },ii); return std::forward
(f);}) .then([](auto o){ std::cout <
all * 1.5) ? 1 : 2; } std::cout<<""<
<<"\n"; return all; },o); return std::forward
(ff);}) .run(2); // 2 seconds std::cout<<"future get : "<
<<"\n";}int main(){ TestTask(); // lambda exec func testFuture(); //lambda exec thread}

转载地址:http://cjxgj.baihongyu.com/

你可能感兴趣的文章
一篇认识 Elasticsearch
查看>>
爬虫篇——腾讯新闻的详细采集过程(列表新闻和新闻内容)
查看>>
NIO 服务器端不阻塞的一个Bug解决
查看>>
DM数据库的安装部署和卸载
查看>>
DM8数据库体系结构
查看>>
DM模式对象的基本操作
查看>>
事件和几个JavaScript实例
查看>>
jQuery基本介绍(和js关系)
查看>>
jQuery选择器和API方法介绍
查看>>
汇编预习三周速成85分之寄存器
查看>>
jQuery对ajax的封装部分详解和案例
查看>>
hibernate简单介绍
查看>>
\hibernate核心配置和映射文件
查看>>
session对象详解
查看>>
hibernate主键生成策略
查看>>
hibernate持久化类以及相互转化
查看>>
汇编笔记之cpu工作原理
查看>>
hibernate的一级缓存
查看>>
hibernate的接口以及表和表之间的关系
查看>>
hibernate产生多余的sql语句
查看>>