Taming Lambdas' uniqueness
summary
C++ lambdas each produce a unique closure type, which breaks passing, storing, or comparing them; concrete fixes are shown: use templates for zero overhead, use std::move_only_function or type erasure when dynamic storage is needed, and prefer indirection or static polymorphism when performance matters. A reusable functors container with an invoke map and cached invokers gets near-template speed and beats std::function; benchmarks report about 3× faster than std::function on GCC and sometimes Clang fully optimizes away indirection.
AI-written summary · about
chapters (34)
- 0:00Lambda uniqueness problem
- 1:28Core problem with identical lambdas
- 3:15C++ unique closure types
- 5:20Non-capturing lambdas to function pointers
- 7:48Capturing lambdas and function pointers
- 10:15Scenario with three different lambdas
- 11:40Passing lambdas via templates
- 13:04std::function and move-only variants
- 16:13Benchmarking lambda passing
- 17:43Storing lambdas in containers
- 19:10Factory for identical lambdas
- 20:58Move-only lambdas in containers
- 22:00Solutions for different signatures
- 23:03Benchmarking lambda storage
- 25:11Performance of std::function
- 26:17Custom type eraser for lambdas
- 28:51Evaluating custom type eraser
- 29:34Syntax for lambda container
- 30:15Static polymorphism with overload
- 32:45Parameter packs and concepts
- 33:46Functors container structure
- 35:09Constructing functors container
- 36:14Deduction guides for container
- 37:17Adding elements to container
- 39:48Handling references in push_back
- 41:10Calling all container lambdas
- 43:59Calling lambdas by index
- 46:05Benchmarking custom container
- 47:07Dynamic dispatch with runtime index
- 48:54Implementing invoke map
- 51:45Performance of invoke map
- 53:14Optimizing invoke map with caching
- 55:20Final benchmarks and takeaways
- 55:41Conclusion and Q&A
related talks
57mC++: λ Demystified
01h 10mThe Three Little Dots and the Big Bad Lambdas
01h 10mstd::function: a deep dive behind the curtain
01h 05mC++11 in the Wild: Techniques from a Real Codebase
01h 09mFunctional Programming in C++
01h 10mstd::function: a deep dive behind the curtain
08mReturn Values Take A Closure Walk
01h 05mIs std::function really the best we can do?
