C ++函数回调:无法从成员函数转换为函数签名 [英] C++ Function Callbacks: Cannot convert from a member function to a function signature

查看:171
本文介绍了C ++函数回调:无法从成员函数转换为函数签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方库,允许我为某些事件注册回调。寄存器功能看起来像这样。它使用Callback签名。

I'm using a 3rd party library that allows me to register callbacks for certain events. The register function looks something like this. It uses the Callback signature.

typedef int (*Callback)(std::string);

void registerCallback(Callback pCallback) {
//it gets registered
}

我的问题是我想注册一个成员函数作为回调,就像这样

My problem is that I want to register a member function as a callback something like this

struct MyStruct {
    MyStruct();
    int myCallback(std::string str);
};

MyStruct::MyStruct() {
    registerCallback(&MyStruct::myCallback);
}

int MyStruct::myCallback(std::string str) {
    return 0;
}

当然,编译器会抱怨说

Of course, the compiler complains, saying


错误C2664:'registerCallback':无法将参数1从'int(__thiscall MyStruct :: *)(std :: string)'转换为'Callback'

error C2664: 'registerCallback' : cannot convert parameter 1 from 'int (__thiscall MyStruct::* )(std::string)' to 'Callback'

我一直在寻找像函数和绑定这样的boost库,但没有一个似乎能够做到这一点。我一直在谷歌搜索的答案,但我甚至不知道该怎么称呼,所以它没有太大的帮助。

I've been looking at boost libraries like function and bind, but none of those seem to be able to do the trick. I've been searching all over Google for the answer, but I don't even know what to call this, so it hasn't been much help.

谢谢提前。

Thanks in advance.

推荐答案

你试图将一个成员函数指针作为一个普通函数指针传递,这是行不通的。成员函数必须将这个指针作为隐藏参数之一,这对于普通函数来说不是这样,所以它们的类型是不兼容的。

You're trying to pass a member function pointer as a normal function pointer which won't work. Member functions have to have the this pointer as one of the hidden parameters, which isn't the case for normal functions, so their types are incompatible.

您可以:

You can:


  1. 更改参数的类型以接受成员函数,并接受一个实例成为调用对象

  2. 退出尝试传递一个成员函数并传递一个普通函数(可能通过使函数 static
  3. li>
  4. 有一个正常的函数,它接受一个类的实例,一个成员函数指针和一个 std :: string ,并使用类似boost 绑定来绑定前两个参数
  5. 使回调注册函数接受一个函子对象或 std :: function (我认为这是个名字)

  6. 其他很多我不会在这里详细介绍的方法,但是你会得到漂移。 b $ b
  1. Change the type of your argument to accept member functions and also accept an instance to be the invoking object
  2. Quit trying to pass a member function and pass a normal function (perhaps by making the function static)
  3. Have a normal function that takes an instance of your class, a member function pointer, and a std::string and use something like boost's bind to bind the first two arguments
  4. Make the callback registration function accept a functor object, or an std::function (I think that's the name)
  5. Numerous other ways which I won't detail here, but you get the drift.

这篇关于C ++函数回调:无法从成员函数转换为函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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