0Pricing
C++ Academy · Lesson

std::function

Store any callable.

std::function is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is std::function?

std::function is a type-erased wrapper that can hold any callable matching a given signature: free functions, lambdas, functors, or bound expressions.

  • Declared with the target signature.
  • Lives in <functional>.
#include <iostream>
#include <functional>

int add(int a, int b) { return a + b; }

int main() {
    std::function<int(int, int)> f = add;
    std::cout << f(2, 3) << '\n';
    return 0;
}

Storing a Lambda

Unlike a raw function pointer, std::function happily stores a lambda, even one with captures.

#include <iostream>
#include <functional>

int main() {
    int offset = 10;
    std::function<int(int)> f = [offset](int x) { return x + offset; };
    std::cout << f(5) << '\n';
    return 0;
}

Storing a Functor

A functor is an object with operator(). std::function can wrap one, calling its operator when invoked.

#include <iostream>
#include <functional>

struct Multiplier {
    int factor;
    int operator()(int x) const { return x * factor; }
};

int main() {
    std::function<int(int)> f = Multiplier{3};
    std::cout << f(4) << '\n';
    return 0;
}

Reassigning the Target

One std::function variable can point at different callables over its lifetime, useful for swapping behavior at runtime.

#include <iostream>
#include <functional>

int main() {
    std::function<int(int)> f = [](int x) { return x + 1; };
    std::cout << f(10) << '\n';
    f = [](int x) { return x * x; };
    std::cout << f(10) << '\n';
    return 0;
}

Empty std::function

A default-constructed std::function holds nothing. Calling it throws std::bad_function_call, so test it first.

#include <iostream>
#include <functional>

int main() {
    std::function<void()> f;
    if (f) {
        f();
    } else {
        std::cout << "empty\n";
    }
    return 0;
}

As a Parameter

Functions can take a std::function parameter to accept any matching callable, making APIs flexible.

#include <iostream>
#include <functional>

void repeat(int n, const std::function<void(int)>& action) {
    for (int i = 0; i < n; ++i) action(i);
}

int main() {
    repeat(3, [](int i) { std::cout << "step " << i << '\n'; });
    return 0;
}

Storing Callbacks

A common use is keeping a callback in a class member so it can be invoked later when an event happens.

#include <iostream>
#include <functional>

struct Button {
    std::function<void()> onClick;
    void click() { if (onClick) onClick(); }
};

int main() {
    Button b;
    b.onClick = [] { std::cout << "clicked!\n"; };
    b.click();
    return 0;
}

A Vector of Callables

Because they share one type, different callables can live together in a container and be invoked in turn.

#include <iostream>
#include <functional>
#include <vector>

int inc(int x) { return x + 1; }

int main() {
    std::vector<std::function<int(int)>> ops;
    ops.push_back(inc);
    ops.push_back([](int x) { return x * 2; });
    for (auto& op : ops) std::cout << op(10) << ' ';
    std::cout << '\n';
    return 0;
}

The Cost of Type Erasure

std::function may allocate memory and adds an indirect call, so it is slightly slower than a direct call or a templated callable. Use it when you need uniform storage.

#include <iostream>
#include <functional>

int main() {
    std::function<int()> f = [] { return 42; };
    int total = 0;
    for (int i = 0; i < 5; ++i) total += f();
    std::cout << total << '\n';
    return 0;
}

Returning a std::function

A factory can build and return a configured callable, letting callers obtain customized behavior.

#include <iostream>
#include <functional>

std::function<int(int)> adder(int n) {
    return [n](int x) { return x + n; };
}

int main() {
    auto add5 = adder(5);
    std::cout << add5(10) << '\n';
    return 0;
}

Comparing to Function Pointers

std::function is more flexible than a function pointer because it stores state, but that flexibility costs a little performance and possibly an allocation.

#include <iostream>
#include <functional>

int main() {
    int base = 7;
    std::function<int(int)> stateful = [base](int x) { return x + base; };
    std::cout << "Stateful result: " << stateful(3) << '\n';
    return 0;
}

Quick Check

Test your understanding of std::function.

Recap

You learned that std::function:

  • wraps any callable matching its signature, including stateful lambdas and functors
  • can be reassigned, stored in containers, and returned from factories
  • throws bad_function_call when empty
  • costs a little overhead from type erasure

Next, you will use std::bind to pre-fill arguments of callables.

Frequently asked questions

Is the “std::function” lesson free?

Yes — the full text of “std::function” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “std::function”?

Store any callable. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “std::function” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Function Pointers
  2. std::function
  3. std::bind
  4. Choosing Callables
← Back to C++ Academy