std::function with non-static member functions

后端 未结 3 725
我寻月下人不归
我寻月下人不归 2021-01-01 22:54

i\'m trying to understand a concept and an error. what\'s wrong with this?

class A
{
public:
    A()
    {
        std::function testFunc(&a         


        
相关标签:
3条回答
  • 2021-01-01 23:03

    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.

    0 讨论(0)
  • 2021-01-01 23:15

    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.)

    0 讨论(0)
  • 2021-01-01 23:24

    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);
    }
    
    0 讨论(0)
提交回复
热议问题