function object研究之三

支持返回类型

目前的function_object_ref版本只能支持void返回类型。我希望能够让它支持多种返回类型,最简单的方法是添加一个模板参数。请看下面的代码:

template<typename function_object_type,typename element_type,typename return_type> class function_object_ref{ public: explicit function_object_ref(function_object_type & object):object_(&object){ } return_type operator()(element_type e){ return object_->operator()(e); } private: function_object_type* object_; }; class compare{ public: compare(int x):x_(x){ } bool operator()(int x){ return x_==x; } int x() const{ return x_; } private: int x_; }; int main(int argc, char** argv) { compare c(2); function_object_ref<compare,int,bool> wrapper_c(c); vector<int>::iterator itor = std::find_if(v.begin(),v.end(),wrapper_c); cout<<*itor; return 0; }

boost::result_of

即将到来的C++11引入了decltype用于编译时推导返回类型。不过目前在我的gcc工程中还没有使用C++11,我引入boost::result_of来帮住解决这个问题。result_of要求function object要定义返回类型result_type.所以上面的代码将减少一个模板参数,示例如下:

template<typename function_object_type,typename element_type> class function_object_ref{ public: explicit function_object_ref(function_object_type & object):object_(&object){ } typename boost::result_of<function_object_type(element_type)>::type operator()(element_type e){ return object_->operator()(e); } private: function_object_type* object_; }; class compare{ public: typedef bool result_type; compare(int x):x_(x){ } bool operator()(int x){ return x_==x; } int x() const{ return x_; } private: int x_; }; int main(int argc, char** argv) { compare c(2); function_object_ref<compare,int> wrapper_c(c); vector<int>::iterator itor = std::find_if(v.begin(),v.end(),wrapper_c); cout<<*itor; return 0; }
感兴趣的可以参考boost文档: http://www.boost.org/doc/libs/1_47_0/libs/utility/utility.htm#result_of
不过个人觉得第二个例子过于复杂。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值