Advertisement
Intermediate C++, Lambda Expressions

What is std::function and how does it relate to lambdas?

Short answer

std::function is a type-erased, general-purpose polymorphic wrapper that can hold any callable (lambda, function pointer, functor) matching a given signature.

Save C++ mock interview
Advertisement
AModel answer
std::function is a type-erased, general-purpose polymorphic wrapper that can hold any callable (lambda, function pointer, functor) matching a given signature. It's useful for storing lambdas in containers or class members where the exact closure type can't be named, at the cost of some overhead versus auto or templates.
std::function<int(int)> f = [](int x){ return x*x; };
std::vector<std::function<void()>> callbacks;
Real-world example
A UI framework stores button callbacks as std::function<void()> so any lambda can be registered.
Likely follow-ups
  • Why not always use auto instead? | What overhead does std::function add?
Related topics