C ++ 11:指向成员函数的指针使用std :: function :: target() [英] C++11: pointers to member function using std::function::target()

查看:2040
本文介绍了C ++ 11:指向成员函数的指针使用std :: function :: target()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已经是一个长期讨论的主题,但我还没有找到满足我的答案。



问题:即使使用C ++ 11的函数:: target()功能,是不可能传递成员函数指针到c风格的方法?



以下代码将无法工作:对mbf.target()的调用将返回0,因此生成一个SEGFAULT。我不明白为什么,因为我将成员函数绑定到一个通用的函数对象,所以类型应该很好。



我做错了什么或我想做不可能的事情?

  #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){}

registerCallback()
{
auto mbMem = mem_fn(& A :: memberCB);
function< void(int,int)> mbf =
bind(mbMem,* this,placeholder :: _ 1,placeholder :: _ 2);
regCallback(* mbf.target< void(*)(int,int)>());
}
};


int main()
{
A inst;
inst.registerCallback();
}


解决方案

类型 void(A :: *)(int,int) c>。因为您尝试转换为错误的类型,因此 target 会返回 nullptr 。我建议只是使 CBType a std :: function< void(int,int)> 。 >

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();
}

解决方案

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

这篇关于C ++ 11:指向成员函数的指针使用std :: function :: target()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆