Can lambdas be defined as data members?
For example, would it be possible to rewrite the code sample below using a lambda instead of a function object?
struct Foo {
std::function<void()> bar;
};
The reason I wonder is because the following lambdas can be passed as arguments:
template<typename Lambda>
void call_lambda(Lambda lambda) // what is the exact type here?
{
lambda();
}
int test_foo() {
call_lambda([] { std::cout << "lambda calling" << std::endl; });
}
I've figured that if a lambda can be passed as a function argument, then maybe they can also be stored as a data member.
After more tinkering I found that this works (but it's kind of pointless):
auto say_hello = [] { std::cout << "Hello"; };
struct Foo {
using Bar = decltype(say_hello);
Bar bar;
Foo() : bar(say_hello) {}
};
std::function
template was introduced precisely as a type eraser for this kind of situations. – Holloweyedbar
a lambda. – Idellaidelle