Implementing type-erasure with std::function in C++
This hard coding problem tests whether you can build a polymorphic function wrapper from first principles using the type-erasure pattern. It is a canonical advanced C++ interview question, often posed only after a candidate demonstrates confidence with templates, inheritance, and memory management.
The core challenge is to store callable objects of different types (function pointers, lambdas, functors) in a single container without knowing their concrete type at compile time. This requires designing an abstract Concept base class and type-specific Impl<Callable> derived classes, then managing heap allocation, copy/move semantics, and proper cleanup. You must also preserve the value category of arguments passed through the call operator and handle the empty-target edge case.
- Virtual function dispatch and abstract base classes
- Copy and move semantics (constructors and assignment)
- Heap memory ownership and RAII
- Perfect forwarding and value category preservation
- Exception safety and error conditions
Interviewers expect you to reason explicitly about ownership, avoid memory leaks, and justify your choice of virtual methods. This problem separates candidates who understand C++ memory and type systems from those who only memorize syntax.