In your simple example, there is no advantage to storing the lambda inside a std::function
. Often, storing a lambda using auto
is more efficient, but it also highly restrictive. The auto
version can serve only as a local variable. If you want to store the lambda for later use, then you must use a std::function
.
For example, you might want to store the lambda inside a class member. Consider the following class:
class Foo
{
std::function<void()> callback_;
public:
void Bar(int value)
{
callback_ = [value] { DoStuff(value); }
}
/* other constructors and methods omitted */
}
In this case, you can't use auto
because the lambda's type is anonymous and only available within the Bar
method.
std::function
is also useful when you want to use lambdas as arguments to regular functions. The function has no way to know the lambda's type, but it can declare a std::function
parameter instead. For example:
void Foo(std::function<void()> callback);
...
Foo([](){ cout << "Lambda" << endl;});
It's worth pointing out that this does not apply to function templates. When using a lambda in such a context, it's usually a better idea to let the compiler deduce the lambda's type (similar to using auto
). For example:
template <class F> void Foo(F&& callback) { /* details */ }
...
Foo([](){ cout << "Lambda" << endl;}