i\'m trying to understand a concept and an error. what\'s wrong with this?
class A
{
public:
A()
{
std::function testFunc(&a
I think the problem you are having is that a member function requires not only a function pointer, but a pointer to the calling object. In other words, member functions have an additional implicit argument that is the pointer to the calling object.
To set a member function to a std::function, you need to use std::bind like this:
std::function<void(int)> testFunc(std::bind(&A::func, this, _1));
This binds the this pointer of the current A instance to the function so it has the function pointer and the object instance, which is enough information to properly call the function. The _1 argument indicates that the first explicit argument will be provided when the function is called.
my question, is it possible to create any sort of object that is able to call a member of a specific instance
In this case the only information that is missing is in fact what specific instance the std::function
object should use: &A::func
can't be used on its own (for instance (this->*&A::func)(0)
uses &A::func
with instance *this
). Try:
std::function<void(int)> testFunc = std::bind(&A::func, this);
(Be careful that std::bind(&A::func, *this)
and std::bind(&A::func, this)
have slightly different semantics.)
With c++11 you can also use lambdas which are slightly easier to read than std::bind
:
index[WM_CREATE] = [this](HWND h, UINT u, WPARAM w, LPARAM l)
{
create(h, u, w, l);
}