function object研究之二

來源:互聯網
上載者:User
如何傳遞引用

<<Effective STL>>提到可以讓function object繼承自unary_function<T, void>,現在來試一下.

class B : public unary_function<int,void>{public:    B():x_(0){    }    void operator()(int x){        cout<<++x_<<endl;    }    int x() const{        return x_;    }private:    int x_;};int main(int argc, char** argv) {    vector<int> v;    v.push_back(1);    v.push_back(2);    A a;    for_each(v.begin(),v.end(),a);    cout<<a.x()<<endl;    cout<<"------------"<<endl;    B b;    typedef vector<int>::iterator itor_type;    for_each<itor_type,B&>(v.begin(),v.end(),b);    cout<<b.x()<<endl;    return 0;}

現在看看unary_function的原始碼,瞭解一下原理。

  template<typename _Arg, typename _Result>    struct unary_function    {      /// @c argument_type is the type of the argument      typedef _Arg      argument_type;      /// @c result_type is the return type      typedef _Result   result_type;    };

這種方法雖然能解決問題,但是需要修改function object的原始碼,而且要在使用for_each的時候顯式的告知模板參數類型(回顧一下前一篇,for_each是一個模板函數,有兩個模板參數),更多時候,我需要一種非侵入式的方式的簡潔方式.
我在實際開發中解決方案之一是採用Pimple模式來處理,也就是B對象擁有一個指標p,指向具體的類,在operator()()中執行p->operator()()操作。Effective STL也提到,這樣的好處就是還可一支援多態,而且避免在值傳遞的時候造成的對象切割。下面看看我自己的實現。

自己實現支援引用傳遞

前面Pimpl模式的解決方案可以給我們一個提示,如果我們有一個模板函數,能夠將function object的地址作為指標儲存在另一個類裡面。這個新類也是一個function object,只不過它的operator()()內部簡單轉調真正的function object,即可。下面的代碼是第一個簡易版本。

template<typename function_object_type,typename element_type>class function_object_ref{public:    explicit function_object_ref(function_object_type & object):object_(&object){    }    void operator()(element_type e){        object_->operator()(e);    }private:    function_object_type* object_;};int main(int argc, char** argv) {    A a2;    function_object_ref<A,int> wrapper(a2);    for_each(v.begin(),v.end(),wrapper);    cout<<a2.x()<<endl;    return 0;}

雖然還有提升空間,但是顯然已經比unary_function的方案簡單多了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.