Skip to content

C++ std::function Tutorial

std::function is a general-purpose polymorphic function wrapper provided in the C++ Standard Library (since C++11). It can store, copy, and invoke any callable target—functions, lambda expressions, bind expressions, or other function objects—whose signature matches its template parameter.


1. Basic Usage

#include <iostream>
#include <functional>

void hello() {
    std::cout << "Hello, world!" << std::endl;
}

int main() {
    std::function<void()> func = hello;
    func(); // Output: Hello, world!
    return 0;
}

2. Storing Lambdas and Functors

#include <iostream>
#include <functional>

int main() {
    std::function<int(int, int)> add = [](int a, int b) { return a + b; };
    std::cout << add(2, 3) << std::endl; // Output: 5

    struct Multiply {
        int operator()(int a, int b) const { return a * b; }
    };
    std::function<int(int, int)> mul = Multiply();
    std::cout << mul(2, 3) << std::endl; // Output: 6
    return 0;
}

3. Passing std::function as a Parameter

#include <iostream>
#include <functional>

void compute(int x, int y, const std::function<int(int, int)>& op) {
    std::cout << op(x, y) << std::endl;
}

int main() {
    compute(2, 3, [](int a, int b) { return a + b; }); // Output: 5
    return 0;
}

4. std::function vs Function Pointer

  • std::function can store lambdas (with captures), functors, and function pointers.
  • Function pointers can only point to free/static functions or static member functions.
#include <iostream>
#include <functional>

void foo() { std::cout << "foo" << std::endl; }

int main() {
    std::function<void()> f1 = foo;
    void (*f2)() = foo;
    f1(); // Output: foo
    f2(); // Output: foo
    return 0;
}

5. Caution: std::function Overhead

  • std::function is flexible but may have more overhead than raw function pointers or functors.
  • For performance-critical code, prefer function pointers or templates if possible.

Summary

  • std::function is a powerful, type-erased wrapper for any callable object.
  • Useful for callbacks, event systems, and generic code.
  • Prefer for flexibility; use function pointers or templates for maximum performance.