|
已根据朋友建议,将汇编改为使用union,所以此次兼容性得到了大幅提高。
支持Borland/CodeGear,Microsoft,GNU,Watcom/OpenWatcom四种C/C++编译器,
在Turbo C++ 2006,Visual C++ 2005,Dev-C++ 4.9,OpenWatcom C/C++ 1.6下测试通过。
- #include<stdio.h>
- #include<stddef.h>
-
- class _Object{};
- typedef void (_Object::*ObjectMemberFunc)(void);
-
- #if defined(SetEventCall)||defined(CallEvent)||defined(DefineEvent)
- #error SetEventCall,CallEvent,DefineEvent 已经定义
- #endif//
-
- #ifdef __BORLANDC__
-
- #define SetEventCall(event_obj,obj,event_func) event_obj=obj->event_func
- #define CallEvent(event_obj) event_obj
- #define DefineEvent(result,name,intro) result (__closure *name)intro
-
- #else
-
- #ifdef _MSC_VER
- #pragma warning(disable:4311) //Microsoft C/C++ 警告
- #endif//
-
- template <typename T> struct EventFunc
- {
- _Object *This;
-
- union
- {
- T Func;
-
- ObjectMemberFunc omf;
- };
- };
-
- #define SetEventCall(event_obj,obj,event_func) {event_obj.This=(_Object *)(void *)obj;event_obj.omf=ObjectMemberFunc(&event_func);}
-
- #define CallEvent(event_obj) (event_obj.This->*(event_obj.Func)) //(*(event_obj.This).*(event_obj.Func))
-
- #define DefineEvent(result,name,intro) EventFunc<result (_Object:: *)intro> name;
- #endif//__BORLANDC__
-
- class Button
- {
- public:
-
- DefineEvent(void,OnClick,(Button *,int)); //定义事件,原型为: void OnClick(Button *,int)
-
- public:
-
- Button()
- {
- printf("Button this=%p\n",this);
- }
-
- void TestButtonClick()
- {
- CallEvent(OnClick)(this,0); //呼叫OnClick,原型为: OnClick(this,0)
- }
- };
-
- class Test
- {
- Button *button;
-
- public:
-
- void OnButtonClick(Button *but,int)
- {
- printf("Test::OnButtonClick,this=%p,but=%p\n",this,but);
- };
-
- public:
-
- Test()
- {
- printf("Test this=%p\n",this);
-
- button=new Button;
-
- SetEventCall(button->OnClick,this,Test::OnButtonClick); //设定button->OnClick事件的处理函数为this->OnButtonClick
-
- button->TestButtonClick();
- }
- };
-
- int main(int,char **)
- {
- Test *test;
-
- #ifdef __BORLANDC__
- printf("Compiler: Borland C/C++ or Turbo C/C++ %d.%d%d\n",(__BORLANDC__>>8),((__BORLANDC__&0xF0)>>4),(__BORLANDC__&0x0F));
- #endif
-
- #ifdef _MSC_VER
- printf("Compiler: Microsoft C/C++ %.2f (Visual C/C++ %.2f)\n",_MSC_VER/100.f,_MSC_VER/100.f-6);
- #endif//
-
- #ifdef __GNUC__
- printf("Compiler: GNU C/C++ %D\n",__GNUC__);
- #endif//__GNUC__
-
- #ifdef __WATCOMC__
- #if __WATCOMC__ < 1200
- printf("Compiler: Watcom C/C++ %.2f\n",__WATCOMC__/100.f);
- #else
- printf("Compiler: OpenWatcom C/C++ %.2f\n",__WATCOMC__/100.f-11);
- #endif//
- #endif//__WATCOMC__
-
- printf("Compile Time: %s %s\n\n",__DATE__,__TIME__);
-
- test=new Test;
-
- delete test;
-
- return(0);
- }
复制代码 |
|