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

Generic lambda expressions

Use case

Generic filtering for any container type.

Explanation

auto in lambda parameters makes the closure’s operator() a template (so one lambda works with any type).

Code

#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>

int main() {
  auto hexPrint = [](auto val) {
    std::cout << "0x" << std::hex << val << "\n";
  };

  // unsigned long = uint64_t
  hexPrint(0x10001000UL);
  // unsigned int = uint32_t
  hexPrint(0xFEEDFACF);

  return 0;
}

View on GitHub.

Output

$ ./src/c++14/build/generic-lambda-expressions
0x10001000
0xfeedfacf