Here is a code:
#include <functional>
using namespace std::tr1;
typedef void(*fp)(void);
void foo(void)
{
}
void f(fp)
{
}
int main()
{
function<void(void)> fun = foo;
f(fun); // error
f(foo); // ok
}
Originally i need to make a function pointer from non-static class method because i need to save data between function callings. I tried std::tr1::bind
and boost::bind
, but they return functional object, not pointer, which, as i can see, can't be "casted" to pure functional pointer. While the function signature (SetupIterateCabinet
) demands a pure func pointer exactly.
I need an advise how to solve the problem. Thank you.
You've greatly oversimplified your real problem and turned your question into an XY problem. Let's get back to your real question: how to call SetupIterateCabinet
with a non-static member function as a callback.
Given some class:
class MyClass
{
public:
UINT MyCallback(UINT Notification, UINT_PTR Param1, UINT_PTR Param2)
{
/* impl */
}
};
In order to use MyClass::MyCallback
as the third argument to SetupIterateCabinet
, you need to pass a MyClass*
for the Context
argument and use a plain shim function to take that Context
argument and do the right thing with it:
UINT MyClassCallback(PVOID Context, UINT Notification, UINT_PTR Param1, UINT_PTR Param2)
{
return static_cast<MyClass*>(Context)->MyCallback(Notification, Param1, Param2);
}
int main()
{
MyClass mc;
SetupIterateCabinet(_T("some path"), 0, MyClassCallback, &mc);
}
You can't convert a std::function
to a function pointer(you can do the opposite). You should use either function pointers, or std::function
s. If you can use std::function
instead of pointers, then you should.
This makes your code work:
typedef function<void(void)> fp;
来源:https://stackoverflow.com/questions/10555464/stdfunction-function-pointer