Learning Hub Search Ctrl K

Modern C++ › C++14

Generic Lambdas and Init Captures

auto parameters and capture by move.

Since C++14 intermediate #lambda#generic-lambda#init-capture#move-capture#auto

Explanation

C++14 makes lambdas more flexible in two ways.

Generic lambdas: declare a parameter auto and the lambda’s operator() becomes a template, so one lambda works for many types.

Init-captures (generalized capture): [name = expression] creates a new variable inside the closure, initialized from any expression. Its main use is capturing by move, which C++11 could not do (a unique_ptr could not be captured at all). You can also use it to compute a value once, or rename a captured member.

Lambdas can also deduce their return type from multiple statements (as long as all returns agree).

Example

#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

int main() {
    auto add = [](auto a, auto b) { return a + b; };       // one lambda, many types
    std::cout << add(1, 2) << " " << add(1.5, 2.5) << " "
              << add(std::string("ab"), std::string("cd")) << "\n";

    std::vector<std::string> words{"pear", "fig", "banana"};
    std::sort(words.begin(), words.end(),
              [](const auto& a, const auto& b) { return a.size() < b.size(); });
    std::cout << words.front() << "\n";                    // fig

    // init-capture: move a unique_ptr into the closure
    auto p = std::make_unique<int>(42);
    auto owner = [ptr = std::move(p)]() { return *ptr; };
    std::cout << owner() << " " << (p == nullptr) << "\n"; // 42 1

    // init-capture: compute once, use many times
    auto scaled = [factor = 2 * 3](int x) { return x * factor; };
    std::cout << scaled(7) << "\n";                        // 42

    // multi-statement body with deduced return type
    auto classify = [](int n) {
        if (n < 0) return std::string("negative");
        if (n == 0) return std::string("zero");
        return std::string("positive");
    };
    std::cout << classify(-3) << "\n";
    return 0;
}

Common pitfalls

  • Every instantiation of a generic lambda is separate code; very generic lambdas in hot headers can bloat binaries.
  • An auto parameter deduces by value; write const auto& (or auto&&) to avoid copies.
  • A move-captured object is const inside a non-mutable lambda, so you cannot move out of it again without mutable.
  • A generic lambda cannot be a plain function pointer once it has captures.
  • All return statements in a lambda with deduced type must give the same type.

Legacy vs modern

In C++11 the same effect required writing a functor class with a templated operator(), or a separate lambda per type. Moving something into a lambda used std::bind tricks. C++20 adds explicit template parameters ([]<typename T>(T a, T b) {...}).

Exercises

1. Write a generic lambda that prints any value followed by a newline.
auto println = [](const auto& v) { std::cout << v << "\n"; };