类函数做为回调函数-解决问题

不关是c.还是c++那么在内存中,数据和程序代码是分开的,代码段和数据段是分开存储的,你声明一个类,他的大小只是数据段数据的大小.既然是这样,那么问题就可以解决了.

代码如下

 

class  EventArgs
{
public:
EventArgs(void) : handled(false) {}
virtual ~EventArgs(void) {}
bool handled;
};
class SlotFunctorBase
{
public:
virtual ~SlotFunctorBase() {};
virtual bool operator()(const EventArgs& args) = 0;
};
template<typename T>
class FunctorPointerSlot : public SlotFunctorBase
{
public:
FunctorPointerSlot(T* functor) :
   d_functor(functor)
   {}
   virtual bool operator()(const EventArgs& args)
   {
    return (*d_functor)(args);
   }
private:
T* d_functor;
};
template<typename T>
class MemberFunctionSlot : public SlotFunctorBase
{
public:
//! Member function slot type.
typedef bool(T::*MemberFunctionType)(const EventArgs&);
MemberFunctionSlot(MemberFunctionType func, T* obj) :
m_lpFunction(func),
  d_object(obj)
{}
virtual bool operator()(const EventArgs& args)
{
  return (d_object->*m_lpFunction)(args);
}
private:
MemberFunctionType m_lpFunction;
T* d_object;
};
class SubscriberSlot
{
public:
SubscriberSlot(){}
~SubscriberSlot(){
  delete d_functor_impl;
};
bool operator()(const EventArgs& args) const
{
  return (*d_functor_impl)(args);
}
bool connected() const
{
  return d_functor_impl != 0;
}
template<class T>
SubscriberSlot(bool (T::*function)(const EventArgs&), T* obj) :
d_functor_impl(new MemberFunctionSlot<T>(function, obj))
{}
template<class T>
SubscriberSlot(T* functor) :
d_functor_impl(new FunctorPointerSlot<T>(functor))
{}
private:
//! Points to the internal functor object to which we are bound
SlotFunctorBase* d_functor_impl;
};

bool  testI(const EventArgs& _art)
{
return true;
}
class CTest
{
public:
static bool Arg(const EventArgs& ev)
{
  return true;
}
void Test()
{
  SubscriberSlot fun(testI);
  EventArgs test;
  fun(test);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest test;
test.Test();
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值