绑定类方法并将其作为函数指针传递

Nic*_*ick 5 c++ bind function c++11

我想将我的类方法作为参数传递给接受函数指针和void*. 下面是一个例子:

#include <functional>

typedef void(*pfnc) (void*);

struct Foo
{
    static void static_foo(void*)
    {
    }

    void foo(void*)
    {
    }

    void listner(pfnc f, void* p)
    {
       f(p);
    }

    void test()
    {
        listner(static_foo); // works with static method

        auto f = [](void*) {};
        listner(f); // works with lambda

        std::function<void(void*)> stdf = std::bind(&Foo::foo, this, std::placeholders::_1);
        listner(stdf);  // does not compile with not static method
    }
};
Run Code Online (Sandbox Code Playgroud)

不幸的是我的解决方案无法编译。我必须改变什么?

Ric*_*ges 1

从回调信号的外观来看,侦听器 API 将指向 void 的指针作为“用户定义的数据”。您可以传递this数据和一个小型无状态代理函数来路由到处理程序Foo

typedef void(*pfnc) (void*);

struct Foo
{
    static void static_foo(void*)
    {
    }

    void foo()
    {
    }

    void listner(pfnc f, void* user_data)
    {

        // eventually calls
        f(user_data);
    }

    void test()
    {
        listner(static_foo, nullptr); // works with static method

        auto f = [](void*) {
        };
        listner(f, nullptr); // works with lambda

        listner([](void* pv)
        {
            reinterpret_cast<Foo*>(pv)->foo();
        }, this);
    }

};
Run Code Online (Sandbox Code Playgroud)