While the template approach is clever for various reasons, it is important to remember the lifecycle of the lambda and the captured variables. If any form of a lambda pointer is is going to be used and the lambda is not a downward continuation, then only a copying [=] lambda should used. I.e., even then, capturing a pointer to a variable on the stack is UNSAFE if the lifetime of those captured pointers (stack unwind) is shorter than the lifetime of the lambda.
A simpler solution for capturing a lambda as a pointer is:
auto pLamdba = new std::function<...fn-sig...>([=](...fn-sig...){...});
e.g., new std::function<void()>([=]() -> void {...}
Just remember to later delete pLamdba
so ensure that you don't leak the lambda memory.
Secret to realize here is that lambdas can capture lambdas (ask yourself how that works) and also that in order for std::function
to work generically the lambda implementation needs to contain sufficient internal information to provide access to the size of the lambda (and captured) data (which is why the delete
should work [running destructors of captured types]).