代码改变世界

2个函数宏技巧

2013-11-21 13:56  Clingingboy  阅读(569)  评论(0编辑  收藏  举报

 

1.用宏调用对象函数

#define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
    do{ \
      CObserverListBase<ObserverType>::Iterator it(observer_list); \
      ObserverType* obs; \
      while((obs=it.GetNext()) != NULL) \
        obs->func; \
    } while(0)

调用方式

//     void NotifyBar(int x, int y) {
//       FOR_EACH_OBSERVER(Observer, observer_list_, OnBar(this, x, y));
//     }

2.用宏定义函数指针来转发

定义:

class TestDelegate
{
public:
    void Test(int i)
    {
        i=1;
    }

    void Test2(int i,int j)
    {
        i=1;
    }

    void (Test22)(int i,int j)
    {
        //((this)->*(&TestDelegate::Test))(i);
    }
};

#define __IMPLEMENT_COMSINK_FUNCTION(func, params, values) \
    typedef void (T::*F##func)params;\
    void Hook_##func(F##func pf##func) \
{ \
    m_pf##func = pf##func; \
} \
    void (func)params \
{ \
    ((m_pT)->*(m_pf##func))values; \
} \
private:\
    F##func m_pf##func;

template<typename T>
class DelegateHandler
{
public:
    DelegateHandler(T* pT,void (T::*pFunc)(int))
        :m_pT(pT),m_pFunc(pFunc)
    {

    }

    __IMPLEMENT_COMSINK_FUNCTION(OnEvent,(int a,int b),(a,b))

private:
    T* m_pT;
    void (T::*m_pFunc)(int);
};

调用

TestDelegate td;
DelegateHandler<TestDelegate> dh(&td,&TestDelegate::Test);
dh.Hook_OnEvent(&TestDelegate::Test2);
dh.OnEvent(4,3);