最接近C# 的Event的C++处理

来源:互联网 发布:淘宝上如何购买发票 编辑:程序博客网 时间:2024/06/08 08:47

最接近C# EventC++处理

 

嗯,最近搞了一点C++,完成了所谓的C++下的Event,懒得多说看代码

#include "boost/function.hpp"

#include "boost/bind.hpp"

#include "iostream"

 

using namespace boost;

using namespace std;

 

template<typename T>

class Event

{

    bool flag;

public:

    typedef boost::function<T> handle_type;

    handle_type Invoke;

 

    Event():flag(false),Invoke()

    {

 

    }

 

    Event& operator= (const boost::function<T>& rhs)

    {

       this->Invoke = rhs;

       flag = true;

       return *this;

    }

 

    void Clear()

    {

       flag = false;

    }

 

    bool IsNull()

    {

       return !flag;

    }

 

};

这样就完成了Event的宣告。用起来实在是很方便,举个小例子

 

比如这里定义一个窗体类:

class Window

{

public:

    Event<void(int)> ClickEvent;   

 

    void test()

    {

       if(!ClickEvent.IsNull())

       {

           ClickEvent.Invoke(100);

       }

    }

};

 

再搞一个测试的片段

void foo(int x)

{

    cout << "x= " << x <<endl;

}

 

class Foo

{

public:

    void foo(int x)

    {

       cout << "foo:: x= " << x <<endl;

    }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

    Window win;

    Foo f;

    win.ClickEvent = bind(&foo,_1);

    win.test();

   

    win.ClickEvent = bind(&Foo::foo,&f,_1);

    win.test();

 

    win.ClickEvent.Clear();

    win.test();

    return 0;

}

是不是一切都很美妙呢!当然你可以直接使用boost::function,不过会有一个小小的问题,你无法来判断boost::function这个东东是不是一个零值,而且每次调用时需要去写一个判断是不是很烦呢?

原创粉丝点击