Fold Expression

Capturing Parameter Packs in Lambdas

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Fold Expression

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Fold Expression

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved