c++ lambdas how to capture variadic parameter pack from the upper scope

后端 未结 3 514
梦如初夏
梦如初夏 2020-12-12 20:43

I study the generic lambdas, and slightly modified the example, so my lambda should capture the upper lambda\'s variadic parameter pack. So basically what is given to upper

3条回答
  •  既然无缘
    2020-12-12 21:10

    The perfect forwarding is another question, I'm curious is it possible here at all?

    Well... it seems to me that the perfect forwarding is the question.

    The capture of ts... works well and if you change, in the inner lambda,

    printer(std::forward(ts)...);
    

    with

    printer(ts...);
    

    the program compile.

    The problem is that capturing ts... by value (using [=]) they become const values and printer() (that is a lambda that receive auto&&...vars) receive references (& or &&).

    You can see the same problem with the following functions

    void bar (int &&)
     { }
    
    void foo (int const & i)
     { bar(std::forward(i)); }
    

    From clang++ I get

    tmp_003-14,gcc,clang.cpp:21:4: error: no matching function for call to 'bar'
     { bar(std::forward(i)); }
       ^~~
    tmp_003-14,gcc,clang.cpp:17:6: note: candidate function not viable: 1st argument
          ('const int') would lose const qualifier
    void bar (int &&)
         ^
    

    Another way to solve your problem is capture the ts... as references (so [&]) instead as values.

提交回复
热议问题