std::function

std::function in C++

std::function is a C++ wrapper that holds any callable with a matching signature, such as a function, lambda or functor, and calls it the same way.

On this page
  1. What std::function is
  2. A first example
  3. Storing a lambda
  4. Storing a functor
  5. Empty wrappers
  6. Passing a std::function to a function
  7. Storing many callables
  8. Capturing by reference
  9. Cost and when to use it
  10. Common mistakes
  11. Summary

What std::function is

std::function is a class template in the <functional> header. It holds something you can call with parentheses, such as an ordinary function, a lambda, a functor (an object with an operator()), or the result of std::bind. Whatever it holds, you call it through the same type. It was added to the standard library in C++11.

You describe the call shape inside the angle brackets:

std::function<int(int, int)>

The type before the parentheses is the return type, and the types inside the parentheses are the argument types. This example type holds any callable that accepts two int values and returns something that converts to int.

Holding different callables behind one type is similar in spirit to polymorphism in c, although std::function does this without inheritance.

A first example

This program stores an ordinary function in a std::function and calls it:

#include <functional>
#include <iostream>

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

int main() {
    std::function<int(int, int)> op = add;

    std::cout << op(2, 3) << '\n';  // prints 5
}

op now refers to add. Calling op(2, 3) runs add and gives back its result.

Storing a lambda

Lambdas are one of the most common things to store. If the lambda syntax is new to you, the basics of c lambda function syntax are worth reading first.

#include <functional>
#include <iostream>

int main() {
    int factor = 3;

    std::function<int(int)> times = [factor](int x) {
        return x * factor;
    };

    std::cout << times(4) << '\n';  // prints 12
}

The lambda captures factor by value, so the wrapper keeps its own copy of that value. Changing factor after the lambda is created does not change what times does.

Storing a functor

A functor is a class or struct with an operator(). A std::function can hold one:

#include <functional>
#include <iostream>

struct Multiplier {
    int factor;

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

int main() {
    std::function<int(int)> times = Multiplier{5};

    std::cout << times(2) << '\n';  // prints 10
}

Functors were a common way to carry data along with a call before lambdas were available. A lambda with captures usually does the same job with less code.

Empty wrappers

A default-constructed std::function holds nothing. Like a pointer, it can be tested in an if statement. Calling an empty one throws std::bad_function_call. Assigning nullptr empties a wrapper again.

#include <functional>
#include <iostream>

int main() {
    std::function<void()> on_click;  // empty: holds nothing

    if (!on_click) {
        std::cout << "No handler yet\n";
    }

    on_click = [] { std::cout << "Clicked\n"; };

    if (on_click) {
        on_click();
    }

    on_click = nullptr;  // empty again
}

Passing a std::function to a function

A parameter of type const std::function<void(int)>& accepts a lambda, a named function or a functor, so the receiving function does not need to be a template:

#include <functional>
#include <iostream>

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

int main() {
    repeat(3, [](int i) { std::cout << i << ' '; });  // prints 0 1 2
    std::cout << '\n';
}

When you only need to pass one named function, c pass function as argument covers the simpler approach.

Storing many callables

All the entries in this vector have the same type, even though each lambda has different code:

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

int main() {
    std::vector<std::function<void()>> tasks;

    tasks.push_back([] { std::cout << "first\n"; });
    tasks.push_back([] { std::cout << "second\n"; });

    for (auto& task : tasks) {
        task();
    }
}

The raw-pointer version of this idea is covered in c array of function pointers.

Capturing by reference

Be careful with lambdas that capture by reference. The reference points to a variable that may no longer exist when the wrapper is called. This version is wrong:

// Undefined behavior: count is destroyed when make_counter returns.
std::function<int()> make_counter() {
    int count = 0;
    return [&count]() { return ++count; };
}

Capture by value and mark the lambda mutable so it can change its own copy:

#include <functional>
#include <iostream>

std::function<int()> make_counter() {
    int count = 0;
    return [count]() mutable {
        return ++count;
    };
}

int main() {
    auto next = make_counter();

    int first = next();   // 1
    int second = next();  // 2

    std::cout << first << ' ' << second << '\n';
}

Each wrapper made this way keeps its own count.

Cost and when to use it

Calling through a std::function usually adds one indirect call compared with calling a function directly. If the stored callable is large, the wrapper may also allocate memory on the heap, and the standard leaves those details to the implementation. For how heap and stack memory differ, see c heap vs stack.

In code that runs many times in a tight loop, a template parameter is often a better fit, because the compiler can usually inline the call. Use std::function when you need to store callables, keep a list of them, or pass them through an interface that uses one fixed type.

Copying a std::function copies the callable it holds, including any values a lambda captured by value.

Common mistakes

  • Mismatched signature. std::function<void(int)> f = add; does not compile, because add takes two int values and returns an int.
  • Missing header. std::function needs #include <functional>.
  • Calling an empty wrapper. This throws std::bad_function_call. Check the wrapper with if first when it might be empty.
  • Capturing locals by reference. A wrapper that refers to a local variable must not outlive that variable. Capture by value instead, as shown above.

Summary

  • std::function<R(Args...)> holds any callable whose result and arguments match R and Args....
  • It can hold function names, lambdas and functors.
  • A new wrapper is empty, so check it before calling.
  • Copying a wrapper copies the callable it holds, including captured values.
  • It adds some call overhead, so a template is often better in a hot loop.

Keep exploring

Guides from other topics

All topics →

The sizeof Operator in C++

Learn how the sizeof operator in C++ works: what it returns in bytes, how it handles arrays, pointers and structs, and common mistakes to avoid.

sizeof 6 min read

Bitwise XOR in C++

Learn how the bitwise XOR operator (^) in C++ works, with a truth table, code examples, and common uses such as toggling bits and swapping values.