具有非静态成员函数的std :: function

时间:2012-04-05 04:42:40

标签: c++ winapi visual-studio-2010

我试图理解一个概念和一个错误。这有什么问题?

class A
{
public:
    A()
    {
        std::function<void(int)> testFunc(&A::func);
    }

private:
    void func(int) {}
}

我的问题是,是否可以创建任何类型的对象,该对象能够调用特定实例的成员,其中std :: function充当成员函数指针,除非没有不能使用的古怪类型定义作为继承类中的函数参数。例如:

class A
{
public:
    A()
    {
         index[WM_CREATE] = &A::close;
         index[WM_DESTROY] = &A::destroy;
    }

protected:
    map<UINT msg, void (A::*)(HWND, UINT , WPARAM, LPARAM)> index;
    void close(HWND,UINT, WPARAM, LPARAM);
    void destroy(HWND, UINT, WPARAM, LPARAM);
};

class B : public A
{
public:
    B()
    {
        index[WM_CREATE] = &B::create; // error because it's not a pointer of type A::*
    }
private:
    void create(HWND, UINT, WPARAM, LPARAM);

};

我在想我正在使用std :: functions这样的正确轨道:

class A
{
public:             //         Gigantic stl error with these two
    A()             //                         |
    {               //                         V
         index[WM_CREATE] = std::function<void(HWND, UINT, WPARAM, LPARAM>(&A::close);
         index[WM_DESTROY] = std::function<void(HWND, UINT, WPARAM, LPARAM>(&A::destroy);
    }

protected:
    map<UINT msg, std::function<void(HWND, UINT, WPARAM, LPARAM)> > index;
    void close(HWND,UINT, WPARAM, LPARAM);
    void destroy(HWND, UINT, WPARAM, LPARAM);
};

class B : public A
{
public:                    //               and this one
    B()                    //                     |
    {                      //                     V
        index[WM_CREATE] = std::function<void(HWND, UINT, WPARAM, LPARAM)>(&B::create);
    }
private:
    void create(HWND, UINT, WPARAM, LPARAM);

};

如果有人能够解释这些巨大的神秘错误是什么意思以及如何修复它们,我将非常感激。

3 个答案:

答案 0 :(得分:14)

我认为你遇到的问题是成员函数不仅需要函数指针,还需要指向调用对象的指针。换句话说,成员函数有一个额外的隐式参数,它是指向调用对象的指针。

要将成员函数设置为std :: function,您需要像这样使用std :: bind:

std::function<void(int)> testFunc(std::bind(&A::func, this, _1));

这将当前A实例的this指针绑定到函数,因此它具有函数指针和对象实例,这足以正确调用函数。 _1参数表示在调用函数时将提供第一个显式参数。

答案 1 :(得分:1)

在c ++ 11中,您还可以使用比std::bind更加易于阅读的lambda:

index[WM_CREATE] = [this](HWND h, UINT u, WPARAM w, LPARAM l)
{
  create(h, u, w, l);
}

答案 2 :(得分:0)

  

我的问题是,是否可以创建任何能够调用特定实例成员的对象

在这种情况下,唯一缺少的信息实际上是std::function对象应该使用的特定实例:&A::func不能单独使用(例如(this->*&A::func)(0)使用实例&A::func的{​​{1}}。尝试:

*this

(请注意std::function<void(int)> testFunc = std::bind(&A::func, this); std::bind(&A::func, *this)的语义略有不同。)

相关问题