C++ · Module 14 · Lesson 51 min read

std::function & Functors

Callables in C++

  • Plain functions / function pointers
  • Functors: objects with operator()
  • Lambdas (unnamed functors)
  • Member functions (via std::mem_fn, std::bind, or lambdas)

Each lambda has a unique type, so you can't put different lambdas in one vector directly…

std::function<R(Args...)> (<functional>)

A type-erased wrapper that can hold any callable with a matching signature:

c
std::function<double(double)> rule;
rule = [](double x) { return x * 0.9; };
rule = apply_tax;                  // a plain function
rule = Discount{0.2};              // a functor
std::vector<std::function<void()>> listeners;
  • Empty std::function → calling it throws std::bad_function_call; check with if (rule)
  • Copies the callable it stores

Cost

Type erasure may allocate memory and uses an indirect call — slightly slower than calling a template parameter directly.

Templates vs std::function ✅

SituationUse
Algorithm parameter used immediately (sort, for_each)template / auto parameter — zero overhead
Need to store callables of different types (callbacks, event handlers, strategy member)std::function
Move-only callables (capturing a unique_ptr)std::move_only_function (C++23)
Non-owning callback parameterstd::function_ref (C++26) or a template

Standard function objects (<functional>)

std::plus<>, std::minus<>, std::multiplies<>, std::less<>, std::greater<>, std::equal_to<>, std::logical_not<> — handy with algorithms.

std::bind and std::mem_fn

Older ways to adapt functions; lambdas are clearer today:

scss
auto add5 = std::bind(add, std::placeholders::_1, 5);   // old
auto add5 = [](int x) { return add(x, 5); };            // ✅

std::invoke

Calls any callable uniformly, including member function pointers: std::invoke(&Account::balance, acc).

Example

C++
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <string>
#include <vector>

double flat_tax(double x) { return x * 1.13; }

struct Discount {
    double rate;
    double operator()(double x) const { return x * (1 - rate); }
};

class EventBus {                                   // stores callbacks of different kinds
public:
    void on(const std::string& event, std::function<void(double)> handler) {
        handlers_[event].push_back(std::move(handler));
    }
    void emit(const std::string& event, double value) const {
        if (auto it = handlers_.find(event); it != handlers_.end())
            for (const auto& h : it->second) h(value);
    }
private:
    std::map<std::string, std::vector<std::function<void(double)>>> handlers_;
};

struct Account {
    double balance = 2500;
    double get() const { return balance; }
};

int main() {
    std::vector<std::pair<std::string, std::function<double(double)>>> rules = {
        { "tax", flat_tax },                                   // function
        { "festival", Discount{ 0.15 } },                      // functor
        { "round", [](double x) { return static_cast<double>(static_cast<long>(x + 0.5)); } },   // lambda
    };
    double price = 1999;
    for (const auto& [name, rule] : rules) {
        price = rule(price);
        std::cout << "after " << name << ": " << price << '\n';
    }

    std::function<void()> empty;
    std::cout << std::boolalpha << "empty function set? " << static_cast<bool>(empty) << '\n';
    try { empty(); } catch (const std::bad_function_call&) { std::cout << "calling it threw bad_function_call\n"; }

    EventBus bus;
    double total_logged = 0;
    bus.on("expense", [](double a) { std::cout << "  notify: spent " << a << '\n'; });
    bus.on("expense", [&total_logged](double a) { total_logged += a; });
    bus.on("income", [](double a) { std::cout << "  notify: earned " << a << '\n'; });
    bus.emit("expense", 450);
    bus.emit("expense", 1200);
    bus.emit("income", 50000);
    std::cout << "total logged expenses: " << total_logged << '\n';

    std::vector<int> v = { 1, 2, 3, 4 };
    std::cout << "product via std::multiplies: " << std::accumulate(v.begin(), v.end(), 1, std::multiplies<>{}) << '\n';

    Account acc;
    std::cout << "std::invoke member function: " << std::invoke(&Account::get, acc)
              << ", member data: " << std::invoke(&Account::balance, acc) << '\n';
    return 0;
}

/* Output:
after tax: 2258.87
after festival: 1920.04
after round: 1920
empty function set? false
calling it threw bad_function_call
  notify: spent 450
  notify: spent 1200
  notify: earned 50000
total logged expenses: 1650
product via std::multiplies: 24
std::invoke member function: 2500, member data: 2500
*/