• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            C++中實現回調機制的幾種方式一文中,我們提到了實現回調的三種方式(C風格的回調函數, Sink方式和Delegate方式)。在面向對象開發中,delegate的方式是最靈活和方便的,因此很早就有人用復雜的模板去模擬(有興趣的話可以看這里這里),總之是實現起來很復雜。但是現在借助C++11的functionbind, 我們可以很方便的去實現。下面是我自己的一種實現方式:
              namespace Common
            {
                typedef void* cookie_type;

                template<typename TR, typename T1, typename T2>
                class CEvent
                {
                public:
                    typedef TR return_type;
                    typedef T1 first_type;
                    typedef T2 second_type;

                    typedef std::function<return_type (first_type, second_type)> handler_type;

                    ~CEvent()
                    {
                        Clear();
                    }

                    return_type operator()(first_type p1, second_type p2)
                    {
                        return_type ret = return_type();
                        size_t size = _handlers.size();
                        for(size_t i=0; i<size; ++i)
                        {
                            ret = _handlers[i]->operator()(p1, p2);
                        }
                        return ret;
                    }

                    cookie_type AddHandler(std::function<return_type (first_type, second_type)> h)
                    {
                        CEventHandler*p = new(nothrow)  CEventHandler(h);
                        if(p != nullptr) _handlers.push_back(p);
                        return (cookie_type)p;
                    }

                    template<typename class_type, typename class_fun>
                    cookie_type AddHandler(class_type* pThis, class_fun f)
                    {
                        CEventHandler* p = new(nothrow) CEventHandler(pThis, f);
                        if(p != nullptr) _handlers.push_back(p);
                        return (cookie_type)p;
                    }

                    void RemoveHandler(cookie_type cookie)
                    {
                        CEventHandler* p = (CEventHandler*)cookie;

                        auto itr = std::find(_handlers.begin(), _handlers.end(), p);
                        if(itr != _handlers.end())
                        {
                            _handlers.erase(itr);
                            delete p;
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    void Clear()
                    {
                        if(!_handlers.empty())
                        {
                            int n = _handlers.size();
                            std::for_each(_handlers.begin(), _handlers.end(), [](CEventHandler* p)
                            { 
                                assert(p != nullptr);
                                delete p;
                            });
                            _handlers.clear();        
                        }
                    }

                private:
                    class CEventHandler 
                    {
                    public:
                        CEventHandler(handler_type h)
                        {
                            _handler = h;
                            assert(_handler != nullptr);
                        }

                        template<typename class_type, typename class_fun>
                        CEventHandler(class_type* pThis, class_fun object_function)
                        {
                            using namespace std::placeholders;
                            _handler = std::bind(object_function, pThis, _1, _2);
                            assert(_handler != nullptr);
                        }

                        return_type operator()(first_type p1, second_type p2)
                        {
                            return_type ret = return_type();
                            assert(_handler != nullptr);
                            if(_handler != nullptr) ret = _handler(p1, p2);
                            return ret;
                        }

                        handler_type _handler;
                    };


                private:
                    std::vector<CEventHandler*> _handlers;
                };
            }

            大概實現思想是我們通過一個內置的CEventHandler 類來封裝處理函數,我們可以通過AddHandler來添加事件處理函數,添加時會返回一個Cookie,我們可以通過該Cookie來RemoveHandler, 下面是測試代碼:
            #include "stdafx.h"
            #include <iostream>
            #include "event1.h"

            using namespace std;

            class CObjectX 
            {

            };

            class CClickEventArgs: public CObjectX
            {

            };


            class CButton: public CObjectX
            {
            public:
                void FireClick()
                {
                    CClickEventArgs args;
                    OnClicked(this, args);
                }

                Common::CEvent<int, CObjectX*, CClickEventArgs&> OnClicked;
            };


            class CMyClass 
            {
            public:
                int OnBtuttonClicked(CObjectX* pButton, CClickEventArgs& args)
                {
                    cout << "CMyClass: Receive button clicked event" << endl;
                    return 1;
                }
            };

            int OnBtuttonClicked_C_fun(CObjectX* pButton, CClickEventArgs& args)
            {
                cout << "C Style Function: Receive button clicked event" << endl;
                return 1;
            }


            class CMyFunObj
            {
            public:
                int operator()(CObjectX* pButton, CClickEventArgs& args)
                {
                    cout << "Functor: Receive button clicked event" << endl;
                    return 1;
                }
            };

            int _tmain(int argc, _TCHAR* argv[])
            {
                using namespace std::placeholders;

                CButton btn;

                CMyClass obj;
                Common::cookie_type c1 = btn.OnClicked.AddHandler(&obj, &CMyClass::OnBtuttonClicked);

                Common::cookie_type c2 = btn.OnClicked.AddHandler(OnBtuttonClicked_C_fun);

                CMyFunObj functor;
                Common::cookie_type c3 = btn.OnClicked.AddHandler(functor);

                btn.FireClick();


                btn.OnClicked.RemoveHandler(c2);

                std::cout << endl;


                btn.FireClick();

                system("pause");

                return 0;
            }

            以下是測試結果:


             可以看到, 我們在普通C函數, 類成員函數和仿函數(functor)中都測試通過。

            另外對于事件函數返回值為void的情況,會編譯出錯,我們需要偏特化一下:
                template< typename T1, typename T2>
                class CEvent<void, T1, T2>
                {
                public:
                    typedef void return_type;
                    typedef T1 first_type;
                    typedef T2 second_type;

                    typedef std::function<return_type (first_type, second_type)> handler_type;

                    ~CEvent()
                    {
                        Clear();
                    }

                    return_type operator()(first_type p1, second_type p2)
                    {
                        size_t size = _handlers.size();
                        for(size_t i=0; i<size; ++i)
                        {
                            _handlers[i]->operator()(p1, p2);
                        }
                    }

                    cookie_type AddHandler(std::function<return_type (first_type, second_type)> h)
                    {
                        CEventHandler*p = new(nothrow)  CEventHandler(h);
                        if(p != nullptr) _handlers.push_back(p);
                        return (cookie_type)p;
                    }

                    template<typename class_type, typename class_fun>
                    cookie_type AddHandler(class_type* pThis, class_fun f)
                    {
                        CEventHandler* p = new(nothrow) CEventHandler(pThis, f);
                        if(p != nullptr) _handlers.push_back(p);
                        return (cookie_type)p;
                    }

                    void RemoveHandler(cookie_type cookie)
                    {
                        CEventHandler* p = (CEventHandler*)cookie;

                        auto itr = std::find(_handlers.begin(), _handlers.end(), p);
                        if(itr != _handlers.end())
                        {
                            _handlers.erase(itr);
                            delete p;
                        }
                        else
                        {
                            assert(false);
                        }
                    }

                    void Clear()
                    {
                        if(!_handlers.empty())
                        {
                            int n = _handlers.size();
                            std::for_each(_handlers.begin(), _handlers.end(), [](CEventHandler* p)
                            { 
                                assert(p != nullptr);
                                delete p;
                            });
                            _handlers.clear();        
                        }
                    }

                private:
                    class CEventHandler 
                    {
                    public:
                        CEventHandler(handler_type h)
                        {
                            _handler = h;
                            assert(_handler != nullptr);
                        }

                        template<typename class_type, typename class_fun>
                        CEventHandler(class_type* pThis, class_fun object_function)
                        {
                            using namespace std::placeholders;
                            _handler = std::bind(object_function, pThis, _1, _2);
                            assert(_handler != nullptr);
                        }

                        return_type operator()(first_type p1, second_type p2)
                        {
                            assert(_handler != nullptr);
                            if(_handler != nullptr) _handler(p1, p2);
                        }

                        handler_type _handler;
                    };


                private:
                    std::vector<CEventHandler*> _handlers;
                };

            最后談一下在寫這個代碼中遇到的問題:
            (1)不知道你能不能發現下面代碼的問題, 我在寫代碼時就栽在這里了:
                 vector<int*>  v;
                int* p1 = new int(1);
                v.push_back(p1);
                int* p2 = new int(2);
                v.push_back(p2);
             
                //嘗試刪除所有值為p1的項
                //由該代碼想到=>v.erase(std::remove(v.begin(), v.end(), p1), v.end());
                //錯誤代碼:
                auto itr = remove(v.begin(), v.end(), p1);
                for_each(itr, v.end(), [](int* p){delete p;});
                v.erase(itr, v.end());

               //正確代碼:
               v.erase(remove_if(v.begin(), v.end(), [](int*p)->bool {if(p==p1) {delete p; return true;} else return false}), v.end());

            (2)我們想把cookei_type放到類里面去, 類似這樣:
            1     template<typename TR, typename T1, typename T2>
            2     class CEvent
            3     {
            4     public:
            5         typedef TR return_type;
            6         typedef T1 first_type;
            7         typedef T2 second_type;
            8         typedef void* cookie_type;

            可發現要這樣使用:
            Common::CEvent<int, CObjectX*, CClickEventArgs&>::cookie_type c1 = btn.OnClicked.AddHandler(&obj, &CMyClass::OnBtuttonClicked);
            太不方便了, 不知道大家有沒有好的方法。

            注:上面的代碼還沒有經過真正商業使用,如果有問題歡迎指出。
            posted on 2013-01-31 14:16 Richard Wei 閱讀(10359) 評論(8)  編輯 收藏 引用 所屬分類: C++

            FeedBack:
            # re: 在C++中實現事件(委托)
            2013-01-31 14:45 | lierlier
            有返回值的事件是需要使用返回策略的,單純返回最后一個值由于回調綁定到事件順序是不確定的,所以實際上無意義  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-01-31 14:49 | Richard Wei
            @lierlier
            確實, 所以.Net里的事件返回類型都都void。這里帶返回值的事件適用于只有一個函數綁定。  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-01-31 16:56 | lierlier
            如果不要求判斷函數是否已經綁定過了,那么有個簡單的做法

            這里保持bind在外邊可以保留靈活性,比如把三個參數的事件處理函數加上一個默認參數綁定到兩個參數的事件上。另外把Event定義為
            template<class A1 = NullT, class A2 = NullT,...>
            這樣的形式,利用偏特化,就可以支持任意個數的事件參數

            代碼:
            #include <map>
            #include <functional>

            using namespace std;


            template<class Arg1, class Arg2>
            class Event
            {
            typedef void HandlerT(Arg1, Arg2);
            int m_handlerId;

            public:
            Event() : m_handlerId(0) {}

            template<class FuncT>
            int addHandler(FuncT func)
            {
            m_handlers.emplace(m_handlerId, forward<FuncT>(func));
            return m_handlerId++;
            }

            void removeHandler(int handlerId)
            {
            m_handlers.erase(handlerId);
            }

            void operator ()(Arg1 p1, Arg2 p2)
            {
            for ( const auto& i : m_handlers )
            i.second(p1, p2);
            }

            private:
            map<int, function<HandlerT>> m_handlers;
            };

            void f1(int, int)
            {
            printf("f1()\n");
            }

            struct F2
            {
            void f(int, int)
            {
            printf("f2()\n");
            }

            void operator ()(int, int)
            {
            printf("f3()\n");
            }
            };

            int _tmain(int argc, _TCHAR* argv[])
            {
            Event<int, int> e;

            int id = e.addHandler(f1);

            e.removeHandler(id);

            using namespace std::placeholders;

            F2 f2;

            e.addHandler(bind(&F2::f, f2, _1, _2));
            e.addHandler(bind(f2, _1, _2));

            e.addHandler([](int, int) {
            printf("f4()\n");
            });

            e(1, 2);

            return 0;
            }  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-01-31 17:36 | Richard Wei
            @lierlier
            多謝指點,感覺你的實現方式對外界比較靈活,性能也比較高。
            而我的實現更強調封裝,適合于在某個框架中使用。  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-02-01 16:49 | zdhsoft
            如果我直接使用bind,是不是明顯比你的靈活多了?初步看了一下,樓主只是在bind上加了一個外殼封裝而已。真正委托的實現,還是交給了bind  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-02-01 17:05 | Richard Wei
            @zdhsoft
            恩,本身就是借助c++11的 function和bind進行封裝  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-02-07 13:32 | Jeff Chen
            我有兩個問題:
            1、為何不使用boost的signal呢?
            2、您的方案與signal相比,有哪些優點,哪些缺點呢?  回復  更多評論
              
            # re: 在C++中實現事件(委托)
            2013-02-07 17:03 | Richard Wei
            @Jeff Chen
            慚愧, 沒研究過boost。
            可能優點就是簡單,可以自己掌控吧,實際上好多公司是禁用boost的。  回復  更多評論
              
            婷婷久久久亚洲欧洲日产国码AV| 久久免费国产精品一区二区| 久久综合狠狠综合久久97色| 国产精品免费久久久久影院 | 国产精品久久毛片完整版| 国产精品美女久久久久久2018| 久久99国产精品久久久| 国产精品免费久久| 欧美日韩精品久久久免费观看| 国产精品久久久久a影院| 久久久久亚洲AV无码网站| jizzjizz国产精品久久| 久久久久噜噜噜亚洲熟女综合| 久久人妻无码中文字幕| 久久综合久久综合九色| 日本精品久久久久久久久免费| 久久综合久久自在自线精品自| 久久精品国产亚洲精品| 韩国免费A级毛片久久| 人妻少妇精品久久| 久久99精品国产99久久6男男| 久久精品国产亚洲AV忘忧草18| yellow中文字幕久久网| 久久精品亚洲精品国产色婷| 综合久久精品色| 人人狠狠综合久久亚洲高清| 久久国产高清一区二区三区| 伊人久久综合热线大杳蕉下载| 奇米综合四色77777久久| 久久人妻AV中文字幕| 免费一级欧美大片久久网| 国产高清美女一级a毛片久久w| 狠狠色婷婷综合天天久久丁香 | 91超碰碰碰碰久久久久久综合| 国产精品久久久久AV福利动漫| 久久亚洲日韩看片无码| 日本精品一区二区久久久| 久久久久人妻精品一区三寸蜜桃| 久久99精品国产麻豆不卡| 26uuu久久五月天| 久久se精品一区精品二区国产|