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 dh(&td,&TestDelegate::Test);
dh.Hook_OnEvent(&TestDelegate::Test2);
dh.OnEvent(4,3);
Original: https://www.cnblogs.com/Clingingboy/p/3435435.html
Author: Clingingboy
Title: 2个函数宏技巧
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/551437/
转载文章受原作者版权保护。转载请注明原作者出处!