Unveiling Type Erasure in C++: From std::function to std::any
summary
Builds a minimal std::function clone that stores heterogeneous callables by wrapping them in a templated function_model, adds a virtual clone() to gain copyable value semantics, and implements small buffer optimization to avoid heap allocation for small callables. Compares that approach to how std::shared_ptr uses type erasure in its control block (storing a deleter) and how std::any can be implemented with a stored typeid plus a manual deleter for manual virtual dispatch. Notes the two real costs: heap allocation and virtual calls.
AI-written summary · about
chapters (10)
- 0:00Introduction and overview
- 1:46The problem of generic design
- 6:46Limitations of inheritance
- 10:37Implementing type erasure
- 17:18Refining the implementation
- 22:34Advanced std::function features
- 32:02Performance optimizations
- 36:24Type safety in standard library
- 45:48Exploring std::any
- 52:05Conclusion and Q&A
