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. One answer suggested using decltype
, which I tried with no success. Here is a ideone source link. The below is the source and result:
#include <cstdio>
auto voidLambda = []()->void{};
class MyClass {
public:
decltype(voidLambda) t;
MyClass(decltype(voidLambda) t) {
this->t = t;
}
};
int main() {
MyClass([] {
printf("hi");
});
}
Result:
prog.cpp: In constructor 'MyClass::MyClass(<lambda()>)':
prog.cpp:3:79: error: no matching function for call to '<lambda()>::__lambda0()'
prog.cpp:2:20: note: candidates are: <lambda()>::<lambda>(const<lambda()>&)
prog.cpp:2:20: note: <lambda()>::<lambda>(<lambda()>&&)
prog.cpp:3:88: error: no match for 'operator=' in '((MyClass*)this)->MyClass::t = t'
prog.cpp: In function 'int main()':
prog.cpp:5:27: error: no matching function for call to 'MyClass::MyClass(main()::<lambda()>)'
prog.cpp:3:48: note: candidates are: MyClass::MyClass(<lambda()>)
prog.cpp:3:14: note: MyClass::MyClass(const MyClass&)
Does anyone know how to do this?
If you want a class member to be a lambda expression, consider using the
std::function<>
wrapper type (from the<functional>
header), which can hold any callable function. For example:This way, you don't need to know the type of the lambda expression. You can just store a
std::function<>
of the appropriate function type, and the template system will handle all the types for you. More generally, any callable entity of the appropriate signature can be assigned to astd::function<>
, even if the the actual type of that functor is anonymous (in the case of lambdas) or really complicated.The type inside of the
std::function
template should be the function type corresponding to the function you'd like to store. So, for example, to store a function that takes in twoint
s and returns void, you'd make astd::function<void (int, int)>
. For a function that takes no parameters and returns anint
, you'd usestd::function<int()>
. In your case, since you want a function that takes no parameters and returnsvoid
, you'd want something like this:Hope this helps!
The only way I can think of to store a lambda in a class is to use a template with a helper
make_
function: