Capturing Parameter Packs in Lambdas

How can I capture a parameter pack in a lambda expression within a fold expression?

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.

Fold Expression

An introduction to C++17 fold expressions, which allow us to work more efficiently with parameter packs

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Fold Expressions with Different Types
Can fold expressions be used with parameter packs containing different types?
Fold Expressions vs Variadic Templates
What are the advantages of using fold expressions over traditional variadic template techniques?
Fold Expressions with Side Effects
Are there any caveats to be aware of when using fold expressions with operations that have side effects?
Empty Parameter Packs in Fold Expressions
How do fold expressions handle empty parameter packs?
Fold Expressions and Constexpr
Can fold expressions be used in constexpr functions?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant