wutiantong
V2EX  ›  C

How to capture perfectly-forwarded variable in lambda ?

  •  
  •   wutiantong · Jun 26, 2019 · 2395 views
    This topic created in 2535 days ago, the information mentioned may be changed or developed.
    template<typename T> do_something(T &&arg) 
    {
        auto lambda = [/* how to capture arg? */] {
            // std::forward<T>(arg)
        };
        lambda();
    }
    
    2 replies    2019-06-27 10:28:43 +08:00
    GeruzoniAnsasu
        1
    GeruzoniAnsasu  
       Jun 26, 2019
    我怎么记得好像在哪看到过这个问题,然后说 lambda 里 capture 到的东西必须是个 lvalue,所以你可以 move,但 move 完它就是个有名字的 lvalue 了,无法作为 rvalue reference capture 下来。


    仅凭印象,没有复查,如果说错了请谅解
    wutiantong
        2
    wutiantong  
    OP
       Jun 27, 2019
    @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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2514 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    ♥ Do have faith in what you're doing.