问题
I know this is already a long discussed topic, but I couldn't yet find an answer that satisfies me.
Question in short: even using the C++11's function::target() capabilities, is it not possible to pass member function pointers to c-style methods?
The following code will not work: the invocation to mbf.target() will return 0 and thus a SEGFAULT is produced. And I don't understand why, because I bind the member function to a generic function object, so the type should be fine.
What am I doing wrong or am I trying to do something impossible?
#include <functional>
using namespace std;
typedef void (*CBType)(int, int);
CBType myCB = 0;
void regCallback(CBType cb)
{
myCB = cb;
}
class A
{
public:
void memberCB(int a, int b) {}
void registerCallback()
{
auto mbMem = mem_fn(&A::memberCB);
function<void(int,int)> mbf =
bind(mbMem, *this, placeholders::_1, placeholders::_2);
regCallback(*mbf.target<void(*)(int,int)>());
}
};
int main()
{
A inst;
inst.registerCallback();
}
回答1:
Your member function is not of type void (*)(int, int)
it is of type void (A::*)(int, int)
. Therefore target
returns nullptr
since you try to cast to the wrong type. I would recommend just making CBType
a std::function<void(int, int)>
.
来源:https://stackoverflow.com/questions/16521644/c11-pointers-to-member-function-using-stdfunctiontarget