🧰Go deeper — read the bookImplement it yourself: the interview classics— runnable code & full walkthrough →

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 function
auto 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 f
int r = f(5); // ops.invoke(storage, 5)
f = square; // reassign - same call site

What this lesson walks through

  1. 01Any callable of one signature
  2. 02Assigning type-erases the callable
  3. 03Inside: storage + an ops table
  4. 04Small buffer vs heap
  5. 05Calling dispatches through invoke
  6. 06Reassign — same call site
  7. 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.

← Previous
CRTP: Static vs Dynamic Polymorphism
Next →
Type Deduction: auto & Templates