c++通知机制

在数据通信中,本层接到数据后,需要交给上层来进一步处理,这个时候通常要用到通知的机制,在c++中有:
1、回调函数
2、虚拟方法
3、函数符(functor)

一、回调函数
在c中一个简单的回调函数是这样的

typedef void(*pcb)(char *) pcb;

void myCallback(pcb callBack, int n)
{
  callBack(n);
}

void perfect(int n)
{
  printf("function prefect called!");
}

void main()
{   myCallback(perfect, n); }

 

在c++中回调函数可以这样   

class Test 
{
public:   
  Test(){};   
  virtual ~Test(){};   
void Handle(string& s, unsigned int lines)   {     for(int i=0; i< lines; i++)     {       cout < < s < < endl;     }   }; }; template < class T> static void CallBack(T& t, boost::function< void (T*, string&, unsigned int)> f) {   string s("test");   f(&t, s, 3); }; int main() {   Test test;   CallBack< Test>(test, &Test::Handle);   return 0; }

 

二、虚拟方法

class NetMsgHandler
{
public:
  NetMsgHandler() : m_nPriority(0) {};
  virtual ~NetMsgHandler() {};
public:
  /**
  * Check if this handler is interest with specified tag.
  * */
  virtual bool    InterestWith(int tag_type) = 0;
  /**
  * Handle the message.
  *@return True if the message is swallowed by this handler.
  *@return False if the message is available for others after this.
  * */
  virtual bool Handle(const codec::SmartData& msg) = 0;
  int GetPriority(void) const { return m_nPriority; };
protected:
  int     m_nPriority;
};

// ConSrvHandle.h
class ConSrvHandle : public NetMsgHandle
{
public:
  /*
  * ... ...
  */
  virtual bool Handle(const codec::SmartData& msg);
}

// ConSrvHandle.cpp
ConSrvHandle::Handle(const codec::SmartData& msg)
{
  // ... ...
}
// 在另外一个文

 

ps: 笔记一个switch 宏定义

#define MSG_DISPATCH_BEGIN(tp,msg) \
bool bHandled = false; \
const SmartData& ref_msg = msg;\
switch( tp ) {

#define MSG_ENTRY(tp_val,fn) \
case tp_val:    \
bHandled = fn( ref_msg );\
break;

#define MSG_DISPATCH_END \
default: break; \
}

MSG_DISPATCH_BEGIN( req_tp,msg )
MSG_ENTRY( LoginType::PT_USER_LOGIN,this->OnUserLoginResult )
MSG_ENTRY( LoginType::PT_ROLE_LOGIN,this->OnRoleLoginResult )
MSG_DISPATCH_END

 

三、函数符(functor)
所谓的仿函数(functor),是通过重载()运算符模拟函数形为的类。

class Comparer
{
public:
  bool operator ()()
  {
  //
  }
}

void SortArray(const Comparer &cmp)
{
  cmp();
}

int main()
{
  SortArray(Comparer());
}

 

注:回调函数是继续自C语言的,因而,在C++中,应只在与C代码建立接口,或与已有的回调接口打交道时,才使用回调函数。除了上述情况,在C++中应使用虚拟方法或函数符(functor),而不是回调函数

 

 

 

posted @ 2014-05-12 11:45  guo_xiao_ping  阅读(1876)  评论(0编辑  收藏  举报