Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 467
bobbel Avatar asked Oct 21 '22 10:10

bobbel


1 Answers

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)>.

like image 199
David Avatar answered Oct 24 '22 02:10

David