liveBook · Manning

Closure

As explained in Learn C++ by Example

A closure is a callable object that packages executable code with captured values from an enclosing scope.

A closure packages executable code with values captured from an enclosing scope. In C++, lambda expressions construct closures, making a small operation easy to keep beside the algorithm that uses it. section 2.3.4 section 2.4

Capture syntax controls how enclosing variables enter the closure: [=] captures used variables by value, while [&x] captures x by reference. Specific combinations such as [=, &x] and [y, &x] make the policy explicit. A closure can also capture nothing when its operation depends only on its parameter. section 2.3.4

Checking a row with a closure

std::all_of(row.begin(), row.end(), [](auto x) { return x >= 0; }) checks every integer without defining a separate named function. The same closure works with the ranges form: std::ranges::all_of(row, [](auto x) { return x >= 0; }). section 2.3.4

Listing 2.14 Making sure there are no negative numbers by using a view
auto negative = [](int x) { return x < 0; };           #1
auto negatives = row | std::views::filter(negative);   #2
assert(negatives.empty());                             #3

A named closure can be reused as a filter predicate, then applied through a view to verify that a row contains no negative values. section 2.3.4

How Learn C++ by Example covers it

How deep it goes
Explains lambda syntax and value or reference capture, but defers fuller closure details.
Examples
Demonstrates non-negative predicates with all_of, ranges::all_of, filter views, and explicit capture-list variants.
What it assumes
Assumes familiarity with parameters and algorithms while introducing lambda syntax, capture lists, and closures.
What you can do after
Apply closures via standard algorithms and ranges to write local predicates and reusable view filters.
How it connects
Connects closures with lambda expressions, standard algorithms, ranges, views, filters, and functional programming.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.