I have used std::bind to create a lambda involving a class member function but boost::signals2 won't accept it.
I have a class Cut
which I would like to inform when there is a new Event
to look at by calling void Cut::newEvent(Event& e)
.
I created a lambda binding to an instance of Cut and this works as expected when I pass it an Event. (The code compiles and the output is "Registered new event".)
However when I try to connect this lambda to an instance of boost::signals2::signal<void(Event&)>
it complains with the message:
error: 'f' cannot be used as a function
which is odd because I can use it as a function in main(). ( I get the same result if I use std::function<void(Event&)>
instead of auto.
Is it possible to make this work? Why doesn't it currently work?
This is relevant code:
#include <iostream>
#include <boost/signals2.hpp>
//Dummy event class
struct Event
{ int val; };
typedef boost::signals2::signal<void (Event&) >
EventBroadcaster;
//Class I want to notified of new events
class Cut
{
public:
void newEvent( Event& e)
{
std::cout << "Registered new event" << std::endl;
fResult = true;
}
bool check() const
{ return fResult; }
private:
bool fResult;
};
int main()
{
Cut c{};
//Lambda to call newEvent on c
auto f =
std::bind( &Cut::newEvent, &c,
std::placeholders::_1) ;
Event e{};
f(e); //works
EventBroadcaster eb;
eb.connect(&f); //doesn't work
}
You should use
eb.connect(f);
since f
is callable function object, but &f
is not callable.