std::function Type-erased Callables
Erase types behind std::function and understand the small-buffer optimization.
The Problem: One Type for Many Callables
Each lambda has a unique type. Each function pointer is a different type. We need one type that can hold any of them — std::function.
Template Parameter
std::function<Signature> takes the return type and parameter types. It accepts anything callable with that signature.
#include <functional>
std::function<int(int, int)> op;
op = [](int a, int b) { return a + b; };
std::cout << op(3, 4); // 7All lessons in this course
- Function Objects Functors
- Lambda Captures by-value by-reference mutable
- Generic Lambdas and Closures C++14
- std::function Type-erased Callables