3: stl & boost functor
stl 和 boost functor提供更强大的功能,不过受制于参数个数的限制。
在前面的1,2中方法里面,可以根据自己的需求定义参数的个数,和函数指针或者成员函数的数量,但是无法
直接把gui层中的成员函数进行帮顶和回调,下面介绍一种模板的实现办法
4:手动写模板
在libraray层中:
- template <class T> class IdrawPoint : public CDrawFPoint
- {
- public:
- typedef int (T::*DRAW_POINT)(int x,int y,RGB rgb);
- typedef int (T::*DRAW_LINE)(int sx,int sy,int ex,int ey,RGB rgb);
- typedef int (T::*DRAW_RECT)(int left,int top,int width,int height,bool fill,RGB rgb);
- typedef int (T::*DRAW_STRING)(const char *str,int x,int y,int font,RGB rgb);
- IdrawPoint(T *obj,DRAW_POINT drawPoint,DRAW_LINE drawLine,DRAW_RECT drawRect,DRAW_STRING drawString)
- {
- m_guiObj = obj;
- m_drawPoint = drawPoint;
- m_drawLine = drawLine;
- m_drawRect = drawRect;
- m_drawString = drawString;
- }
-
- int drawPoint(int x,int y,RGB rgb){
- return (m_guiObj->*m_drawPoint)(x,y,rgb);
- }
- int drawLine(int sx,int sy,int ex,int ey,RGB rgb)
- {
- return (m_guiObj->*m_drawLine)(sx,sy,ex,ey,rgb);
- }
- int drawRect(int left,int top,int width,int height,bool fill,RGB rgb)
- {
- return (m_guiObj->*m_drawRect)(left,top,width,height,fill,rgb);
- }
- int drawString(const char *str,int x,int y,int font,RGB rgb)
- {
- return (m_guiObj->*m_drawString)(str,x,y,font,rgb);
- }
- private:
- T *m_guiObj;
- DRAW_POINT m_drawPoint;
- DRAW_LINE m_drawLine;
- DRAW_RECT m_drawRect;
- DRAW_STRING m_drawString;
- };
- 在library的接口类中定义
- void accept(class CDrawFPoint *fp){m_fp = fp;}
- CDrawFPoint *m_fp;
在gui层中可以在类的成员函数中直接实现CDrawFPoint 的接口而不需要继承此类
- class MyGuiLevel{
- public:
- MyGuiLevel();
- ~MyGuiLevel();
- void init();
- int drawPoint(int x,int y,RGB rgb){return 1;}
- int drawLine(int sx,int sy,int ex,int ey,RGB rgb){return 1;}
- int drawRect(int left,int top,int width,int height,bool fill,RGB rgb){return 1;}
- int drawString(const char *str,int x,int y,int font,RGB rgb){return 1;}
- };
- void MyGuiLevel::init()
- {
-
- IdrawPoint *guiDrawFPoint;
- guiDrawFPoint = new IdrawPoint(this,&MyGuiLevel::drawPoint,
- &MyGuiLevel::drawLine,
- &MyGuiLevel::drawRect,
- &MyGuiLevel::drawString);
-
- }
这种设计办法library无需关心gui层的具体任何实现,此处利用了虚拟函数和模板的的办法实现了
将一个成员函数直接注册给底层的办法。
阅读(1731) | 评论(0) | 转发(0) |