我需要将一个方法绑定(bind)到一个函数回调中,除了这个片段是不合法的,如 demote-boostfunction-to-a-plain-function-pointer 中所讨论的那样.
获得此行为的最简单方法是什么?
struct C {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::function<void (int x)> cb = boost::bind(&C::m, &c, _1);
cb_t raw_cb = *cb.target<cb_t>(); //null dereference
raw_cb(1);
return 0;
}
最佳答案
您可以创建自己的类来执行与 boost 绑定(bind)函数相同的操作。该类所要做的就是接受函数类型和指向包含该函数的对象的指针。例如,这是一个 void return 和 void param 委托(delegate):
template<typename owner>
class VoidDelegate : public IDelegate
{
public:
VoidDelegate(void (owner::*aFunc)(void), owner* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
~VoidDelegate(void)
{}
void Invoke(void)
{
if(mFunction != 0)
{
(mOwner->*mFunction)();
}
}
private:
void (owner::*mFunction)(void);
owner* mOwner;
};
用法:
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
现在,自 VoidDelegate<C>
是一种类型,拥有这些的集合可能不切实际,因为如果列表也包含类 B 的函数怎么办?它不能。
这就是多态性发挥作用的地方。您可以创建一个接口(interface) IDelegate,它具有一个函数 Invoke:
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
如果VoidDelegate<T>
实现 IDelegate,您可以拥有 IDelegates 的集合,因此可以回调不同类类型的方法。
关于c++ - 来自绑定(bind)方法的原始函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/516411/