我正在使用第 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.
您可以:
static
)std::string
并使用类似 boost 的 bind
的东西来绑定第一个两个参数std::function
(我认为这就是名字)static
)std::string
and use something like boost's bind
to bind the first two argumentsstd::function
(I think that's the name)这篇关于C++ 函数回调:无法从成员函数转换为函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!