问题描述
我需要一个方法绑定到一个函数回调,但这个片段是不合法的作为demote-boostfunction-to-a-plain-function-pointer.
什么是获得这一行为最简单的方法?
结构13C {
无效米(INT X){
(无效)×;
_asm INT 3;
}};无效的typedef(* cb_t)(INT);
诠释主(){
C C;
提振::函数<无效(INT X)> CB =的boost ::绑定(和C ::男,和C,_1);
cb_t raw_cb = * cb.target< cb_t>(); //空取消引用
raw_cb(1);
返回0;
}
您可以使自己的课上做同样的事情升压绑定功能。所有的类所要做的就是接受函数类型和一个指向包含该函数的对象。例如,这是返回void和无效参数委托:
模板< typename的所有者>
类VoidDelegate:公共IDelegate
{
上市:
VoidDelegate(无效(所有者:: * aFunc)(无效),所有者* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
〜VoidDelegate(无效)
{}
无效调用(无效)
{
如果(mFunction!= 0)
{
(mOwner-> * mFunction)();
}
}私人的:
无效(所有者:: * mFunction)(无效);
所有者* mOwner;
};
用法:
C类
{
无效的CallMe(无效)
{
性病::法院LT&;< 所谓的;
}
};
INT主(INT aArgc,焦炭** aArgv)
{
C C;
VoidDelegate&所述c取代;委托(和C ::的CallMe,和C);
delegate.Invoke();
}
现在,因为 VoidDelegate< C>
是一种类型,有这些的集合可能是不实际的,因为如果有什么的名单是含有B类的功能太?这是不可能的。
这就是多态性的用武之地。你可以创建一个接口IDelegate,其中有一个函数调用:
类IDelegate
{
虚拟〜IDelegate(无效){}
虚拟无效调用(无效)= 0;
}
如果 VoidDelegate< T>
实现IDelegate你可以有IDelegates的集合,因此有回调在不同的类类型的方法
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.
What's the simplest way to get this behavior?
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;
}
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;
};
Usage:
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
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.
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;
}
If VoidDelegate<T>
implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types.
这篇关于从绑定的方法原始函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!