Skip to content
Justice Tech School

std::function and Callbacks

std::function stores any callable: functions, lambdas and functors. Pass callbacks to algorithms and event handlers.

Example
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
struct Mul { int k; int operator()(int x) const { return x * k; } };
int main() {
    function<int(int)> f = [](int x) { return x + 1; };
    cout << f(4) << "\n";
    f = Mul{3};
    cout << f(4) << "\n";
    vector<function<void()>> tasks;
    for (int i = 1; i <= 2; i++) tasks.push_back([i] { cout << "task " << i << "\n"; });
    for (auto &t : tasks) t();
}

Result

5
12
task 1
task 2

Exercise

Store a callable.

std::<int(int)> f

Quiz Test

What can std::function hold?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.