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.
您可以:
- 更改参数类型以接受成员函数并接受一个实例作为调用对象
- 不再尝试传递成员函数并传递普通函数(可能通过使函数
static
) - 有一个普通函数,它接受你的类的一个实例、一个成员函数指针和一个
std::string
并使用类似 boost 的bind
的东西来绑定第一个两个参数 - 让回调注册函数接受一个函子对象,或者一个
std::function
(我认为这就是名字) - 我不会在此详述的许多其他方式,但您会有所了解.
- Change the type of your argument to accept member functions and also accept an instance to be the invoking object
- Quit trying to pass a member function and pass a normal function (perhaps by making the function
static
) - Have a normal function that takes an instance of your class, a member function pointer, and a
std::string
and use something like boost'sbind
to bind the first two arguments - Make the callback registration function accept a functor object, or an
std::function
(I think that's the name) - Numerous other ways which I won't detail here, but you get the drift.
相关文章