如何傳遞引用
<<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的方案簡單多了。