c++ lambdas 如何从上层范围捕获可变参数包
问题描述
我研究了通用 lambda 表达式,并稍微修改了示例,所以我的 lambda 应该捕获上层 lambda 的可变参数包.所以基本上什么是给上层 lambda 的 (auto&&...) - 应该以某种方式在
[=]
块中捕获.
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 lambda as (auto&&...)
- should be somehow captured in [=]
block.
(完美转发是另一个问题,我很好奇这里有可能吗?)
(The perfect forwarding is another question, I'm curious is it possible here at all?)
推荐答案
C++20 中的完美捕获
<小时>
C++17 和 C++14 解决方法
在 C++17 中,我们可以使用元组的解决方法:
In C++17 we can use a workaround with tuples:
不幸的是
>std::apply
是 C++17,在 C++14 中你可以自己实现它或者用 boost::hana
做类似的事情:
Unfortunately std::apply
is C++17, in C++14 you can implement it yourself or do something similar with boost::hana
:
通过函数capture_call
来简化解决方法可能会很有用:
It might be usefull to simplify the workaround by a function capture_call
:
像这样使用它:
<小时>
这是capture_call
的C++14实现:
<小时>
capture_call
按值捕获变量.完美意味着尽可能使用移动构造函数.下面是一个 C++17 代码示例,以便更好地理解:
capture_call
captures variables by value. The perfect means that the move constructor is used if possible. Here is a C++17 code example for better understanding:
输出:
捕获值的类型在capture_call
版本中包含&&
,因为我们必须通过引用访问内部元组中的值,而支持的语言capture 支持直接访问值.
The type of the capture value contains &&
in the capture_call
version because we have to access the value in the internal tuple via reference, while a language supported capture supports direct access to the value.
这篇关于c++ lambdas 如何从上层范围捕获可变参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!