When using a lambda expression within a fold expression, you can capture the parameter pack directly from the outer function's scope using the capture list of the lambda.
Here's an example that demonstrates capturing a parameter pack in a lambda:
#include <iostream>
template <typename... Types>
void PrintValues(Types... Args) {
([&] { std::cout << Args << ' '; }(),
...);
std::cout << '\n';
}
int main() { PrintValues(42, 3.14, "hello"); }
42 3.14 hello
In this example, the lambda expression captures Args
by reference using [&]
in its capture list. This allows the lambda to access each element of the parameter pack Args
from the outer PrintValues()
function's scope.
The fold expression (... , lambda())
expands to multiple invocations of the lambda, once for each element in Args
. Each invocation prints the corresponding element followed by a space.
Capturing the parameter pack by reference ([&]
) is often sufficient. However, if you need to capture by value, you can use [=]
 instead:
#include <iostream>
template <typename... Types>
void PrintValues(Types... Args) {
([=] { std::cout << Args << ' '; }(), ...);
std::cout << '\n';
}
int main() { PrintValues(42, 3.14, "hello"); }
42 3.14 hello
Capturing by value creates a copy of each element in the parameter pack within the lambda's closure.
Remember that capturing parameter packs in lambdas is only necessary when you want to use the parameter pack directly within the lambda's body. If you pass the parameter pack as an argument to the lambda, capturing is not required.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to C++17 fold expressions, which allow us to work more efficiently with parameter packs