cpp core · advanced
Type Erasure & std::function
std::function type-erases any callable of a signature: it stores the callable (small-buffer or heap) plus an ops table, and dispatches through it.
🔑 Key line
Type erasure (std::function) wraps any callable behind a uniform interface via stored ops (invoke/copy/destroy) - at the cost of indirection, maybe heap, and no inlining.
The code
int square(int x); // free functionauto lam = [k](int x) { return x * k; }; // lambda (captures k)struct Mul { int operator()(int) const;}; // functor
std::function<int(int)> f = lam; // type-erased into fint r = f(5); // ops.invoke(storage, 5)f = square; // reassign - same call siteWhat this lesson walks through
- 01Any callable of one signature
- 02Assigning type-erases the callable
- 03Inside: storage + an ops table
- 04Small buffer vs heap
- 05Calling dispatches through invoke
- 06Reassign — same call site
- 07Type erasure in one line
std::function<int(int)> can hold any callable matching that signature - a function pointer, a lambda (even with captures), or a functor. Three different concrete types.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Type Erasure & std::function and 100+ animated C++ interview lessons.