← C++ Index

λ <functional> — Lambdas, std::function, std::bind

Higher-order programming in C++. std::function is a type-erased callable wrapper. Lambda expressions (C++11) are the most common way to pass callbacks.

Include: #include <functional> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::function<R(Args…)>class templateStore any callable: lambda, fn ptr, functor
std::bind(fn, args…)bind_exprPartially apply arguments to a callable
std::placeholders::_1placeholderArgument placeholder for std::bind
std::ref(x)reference_wrapperPass x by reference through bind
std::invoke(fn, args…)RCall any callable with args (C++17)
[](){…}lambdaLambda with no captures
[=](){…}lambdaLambda capturing all by value
[&](){…}lambdaLambda capturing all by reference
[x, &y](){…}lambdaCapture x by value, y by reference

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;

void apply_all(const vector<int> &v, function<void(int)> fn) {
    for (int x : v) fn(x);
}

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};

    cout << "Elements: ";
    apply_all(nums, [](int x){ cout << x << " "; });
    cout << "\n";

    int threshold = 3;
    vector<int> big;
    for_each(nums.begin(), nums.end(),
        [&big, threshold](int x){ if (x > threshold) big.push_back(x); });
    cout << "Above " << threshold << ": ";
    for (int x : big) cout << x << " ";
    cout << "\n";

    auto multiply = [](int a, int b){ return a * b; };
    auto double_it = bind(multiply, placeholders::_1, 2);
    cout << "double_it(7) = " << double_it(7) << "\n";

    function<int(int,int)> op = [](int a, int b){ return a + b; };
    cout << "add(3,4)  = " << op(3, 4) << "\n";
    op = [](int a, int b){ return a * b; };
    cout << "mul(3,4)  = " << op(3, 4) << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o functional_demo functional_demo.cpp

← <thread>  |  🏠 Index  |  <optional> →