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:
std::function<int()> myFunction = []() { return 0; }
myFunction(); // Returns 0;
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 a std::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 two int
s and returns void, you'd make a std::function<void (int, int)>
. For a function that takes no parameters and returns an int
, you'd use std::function<int()>
. In your case, since you want a function that takes no parameters and returns void
, you'd want something like this:
class MyClass {
public:
std::function<void()> function;
MyClass(std::function<void()> f) : function(f) {
// Handled in initializer list
}
};
int main() {
MyClass([] {
printf("hi")
}) mc; // Should be just fine.
}
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…