Simplest C++ callback, from SumatraPDF
16 points by raymii
16 points by raymii
I don’t really understand what problem this is solving, but then I also didn’t find the implementation of std::function that hard to understand. It has a private class that exposes an invoke method as a virtual function. This is a templated class that owns a T and calls it. The T is stored inline if it’s small or copied to the heap if it’s big. This is a simple type-erasure pattern: it lets you capture a wrapped T and invoke it with virtual functions without needing to know the concrete type of T except at the point where the wrapper is created. The size and vtable layout of the wrapper are known so can be passed into non-templated code. There are a few special cases that avoid some indirection for common cases.
A C++ lambda is just syntactic sugar. It’s an object with a non-virtual operator::()
method that captures all referenced things as fields in the object and then has access to them from the call-as-function method. You can create these yourself trivially (you can implement lambdas purely as a source-to-source transform).
The only downside to std::function is that it heap allocates because the captured data can be different sizes. I prefer: https://github.com/WG21-SG14/SG14/blob/master/SG14/inplace_function.h