V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wutiantong
V2EX  ›  C

How to capture perfectly-forwarded variable in lambda ?

  •  
  •   wutiantong · 2019-06-26 10:41:51 +08:00 · 1724 次点击
    这是一个创建于 1767 天前的主题,其中的信息可能已经有所发展或是发生改变。
    template<typename T> do_something(T &&arg) 
    {
        auto lambda = [/* how to capture arg? */] {
            // std::forward<T>(arg)
        };
        lambda();
    }
    
    2 条回复    2019-06-27 10:28:43 +08:00
    GeruzoniAnsasu
        1
    GeruzoniAnsasu  
       2019-06-26 19:34:39 +08:00
    我怎么记得好像在哪看到过这个问题,然后说 lambda 里 capture 到的东西必须是个 lvalue,所以你可以 move,但 move 完它就是个有名字的 lvalue 了,无法作为 rvalue reference capture 下来。


    仅凭印象,没有复查,如果说错了请谅解
    wutiantong
        2
    wutiantong  
    OP
       2019-06-27 10:28:43 +08:00
    @GeruzoniAnsasu 你说的是对的呀,C++14 里引入了带 initializer 的 capture 以此来解决 move 的问题,但这个语法仅限于通过 auto 或者 auto &来自动推断类型,所以不能直接得到 rvalue ref
    然后针对 perfectly-forward 的情况就需要通过一些 wrapper 的手段来绕一下,我搜到的这篇文章讲了很详细:
    https://vittorioromeo.info/index/blog/capturing_perfectly_forwarded_objects_in_lambdas.html
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   886 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:23 · PVG 04:23 · LAX 13:23 · JFK 16:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.