I\'ve been thinking about storing C++ lambda\'s lately. The standard advice you see on the Internet is to store the lambda in a std::function object. However, none of this adv
The problem is that std::function doesn't use move semantics and copies the lambda around while initializating. It's a bad implementation by MS.
Here is a little trick you can use to get around the problem.
template
class move_lambda
{
T func_;
public:
move_lambda(T&& func) : func_(std::move(func)){}
move_lambda(const move_lambda& other) : func_(std::move(other.func_)){} // move on copy
auto operator()() -> decltype(static_cast(0)()){return func_();}
};
template
move_lambda make_move_lambda(T&& func)
{
return move_lambda(std::move(func));
}
usage:
int main()
{
Simple test( 5 );
std::function f(make_move_lambda(
[test] ()
{
return test.Get();
}));
printf( "%d\n", f() );
}