来自绑定方法的原始函数指针 [英] raw function pointer from a bound method
问题描述
我需要将一个方法绑定到一个函数回调中,除非这个代码段不合法,如 demote-boostfunction-to-a-plain-function-pointer 。
I need to bind a method into a function-callback, except this snippet is not legal as discussed in 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绑定函数相同的事情。所有的类都要做的是接受函数类型和一个指向包含该函数的对象的指针。例如,这是一个void return和void param delegate:
You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and 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的函数呢?它不能。
Now, since VoidDelegate<C>
is a type, having a collection of these might not be practical, because what if the list was to contain functions of class B too? It couldn't.
这是多态性发挥的地方。你可以创建一个接口IDelegate,它有一个函数Invoke:
This is where polymorphism comes into play. You can create an interface IDelegate, which has a function Invoke:
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
如果 VoidDelegate< T>
implements IDelegate你可以有一个IDelegates的集合,因此有回调到不同类类型的方法。
If VoidDelegate<T>
implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types.
这篇关于来自绑定方法的原始函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!