C++11: pointers to member function using std::function::target()

烈酒焚心 提交于 2019-12-10 14:04:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!