Reputation: 2208
I'm trying to implement a c++ function that gets a Lambda callback as a parameter. The thing is, the callback is initiated asynchronously from another function in the same (called) class. I therefore need to store the Lambda in a member variable so that it can be accessed by the asynchronous function that needs to initiate the callback.
I tried all the ways I could think of to declare, set and call the Lambda using a member variable, but the code always crashes either in the assignment or in the call.
Here's a stripped-out version of what I'm trying to do.
Declaring the function:
void function(const std::function<void()>callback);
Calling the function from the main code:
myClass->function([](){cout << "Callback called";});
If I execute callback
from within function
it works fine, but I couldn't find a way to store it in a member variable (e.g. m_callback
) and invoke it from another function of the same class.
Upvotes: 3
Views: 4596
Reputation: 64223
Just create a std::function variable, and call it.
#include <iostream>
#include <functional>
struct A{
std::function<void()> cb;
void function(const std::function<void()>callback){
cb=callback;
}
};
int main() {
A a;
a.function([](){std::cout << "Callback called";});
a.cb();
}
Upvotes: 1
Reputation: 477040
This should work:
#include <functional>
#include <utility>
struct MyThing
{
std::function<void()> f_;
void SetCallback(std::function<void()> f) { f_ = std::move(f); }
void Action() { f_(); }
};
Usage:
#include <iostream>
MyThing thing;
thing.SetCallback([](){ std::cout << "Boo\n"; });
thing.Action();
Upvotes: 5