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, becauseaddtakes twointvalues and returns anint. - Missing header.
std::functionneeds#include <functional>. - Calling an empty wrapper. This throws
std::bad_function_call. Check the wrapper withiffirst 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 matchRandArgs....- 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.