I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.
A sample code to illustrate my problem :
#include <iostream>
class Event
{
public:
std::string type;
Event(std::string type):type(type){}
};
class EventDispatcherBase
{
public:
void addEventListener(std::function<void(Event &event)> listener)
{
Event myEvent("Type of the myEvent object");
listener(myEvent);
}
};
class EventDispatcherClass:public EventDispatcherBase
{
public:
EventDispatcherClass()
{
addEventListener([](Event &event){std::cout << event.type << std::endl;});
//addEventListener([this]{listener(Event event);});
};
void listener(Event &event)
{
std::cout << event.type << std::endl;
}
};
int main()
{
EventDispatcherClass eventDispatcherClass;
return 0;
}
This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line
addEventListener([this]{listener(Event event);});
in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :
no viable conversion from '(lambda at .../main.cpp:27:26)' to 'std::function'
I don't understand why.