Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lambda capture of parameter pack

Use case

Capture variadic args in a lambda.

Explanation

...args in capture expands pack. Each element capture separately.

Code

#include <cstdint>
#include <iostream>

template <typename... Args> auto makeLogger(Args &&...args) {
  return [... captures = std::forward<Args>(args)]() {
    std::cout << std::hex;
    ((std::cout << captures << " "), ...);
    std::cout << "\n";
  };
}

int main() {
  auto log = makeLogger("Symbol:", "_main", "@", 0x10001000);
  log();
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/lambda-capture-of-parameter-pack
Symbol: _main @ 10001000