I\'d like to create a class where the client can store a lambda expression like []() -> void {} as a field of the class, but I can\'t figure out how to do so
In case of void () simple function pointer can be used (declaration syntax is void (*pointer_name) ();). Lambda with empty capture block is implicitly convertible to function pointer with same signature. And std::function have runtime and size (std::function is at least three times larger) overhead.
struct S
{
void (*f_p)() {}; // `{}` means `= nullptr`;
};
int main()
{
S s { [] { std::cout << "Lambda called\n"; }};
s.f_p();
S s2;
if (s2.f_p) // check for null
s.f_p();
s2.f_p = [] { std::cout << "Lambda2 called\n"; };
s2.f_p();
s2.f_p = std::terminate; // you can use regular functions too
s2.f_p();
}
Output
Lambda called
Lambda2 called
terminate called without an active exception