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

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

问题描述

我正在使用第 3 方库,它允许我为某些事件注册回调.register 函数看起来像这样.它使用回调签名.

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'

我一直在寻找像 function 和 bind 这样的 boost 库,但似乎没有一个能够做到这一点.我一直在 Google 上到处搜索答案,但我什至不知道该怎么称呼它,所以没有太大帮助.

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.

提前致谢.

推荐答案

您正试图将成员函数指针作为普通函数指针传递,但该指针不起作用.成员函数必须将this指针作为隐藏参数之一,普通函数不是这样,因此它们的类型不兼容.

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.

您可以:

  1. 更改参数类型以接受成员函数并接受一个实例作为调用对象
  2. 不再尝试传递成员函数并传递普通函数(可能通过使函数static)
  3. 有一个普通函数,它接受你的类的一个实例、一个成员函数指针和一个 std::string 并使用类似 boost 的 bind 的东西来绑定第一个两个参数
  4. 让回调注册函数接受一个函子对象,或者一个std::function(我认为这就是名字)
  5. 我不会在此详述的许多其他方式,但您会有所了解.
  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天全站免登陆