我想通过我的类方法作为参数传递给一个(第三方)功能 (听者 - 不能改变),它接受一个函数指针和一个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
}
};
不幸的是,我的解决方案不能编译。我需要改变什么?
函数指针没有状态。你将不得不使用'void *'参数。从另一方面来说,这个参数是存在的,与我遇到的其他一些特定的C API不同。 – chris
你确定'listener'方法只接受'pfnc'吗?通常这样的方法接受用户指定的'void *'参数,该参数在回调处理器方法期间传递... –
我通常使用一个lambda来捕获此方法来调用该方法。 –