Type Erasure and the Cost of a Callable

A reported C++ interview track asks about std::function alongside RAII and std::move, and it is a well-chosen question: answering it properly requires explaining type erasure, which is the technique behind half the standard library's flexibility and most of its hidden costs.

The problem type erasure solves

A lambda has a unique, unnameable type. Two lambdas taking an int and returning void are different types with nothing in common, so a container cannot hold both and a function cannot take either without being a template.

std::function<void(int)> is one type that can hold any of them. It does that by storing the callable behind an interface it synthesises: a pointer to the object, and a small table of operations, call, copy, destroy, that know the concrete type. That is type erasure. The type is not really erased, it is hidden behind a uniform interface generated per stored type.

The rest of this lesson is for subscribers

Unlock every lesson in Systems Programming for Trading, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Systems Programming for Trading

19 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them