std::function
Store any callable.
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;
}All lessons in this course
- Function Pointers
- std::function
- std::bind
- Choosing Callables