`
阿尔萨斯
  • 浏览: 4185614 次
社区版块
存档分类
最新评论

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.所以减少一个模板参数的同时,又在函数对象中增加了一个typedef,示例如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/utility/result_of.hpp>
using namespace std;

template<typename FunctionObjectType, typename ElementType>
class FunctionObjectRef {
public:
    explicit FunctionObjectRef(FunctionObjectType & object): object_(&object) {

    }

    typedef typename boost::result_of<FunctionObjectType(ElementType)>::type ReturnType;
    
    ReturnType operator()(ElementType e) {
        return object_->operator()(e);
    }
private:
    FunctionObjectType* 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) {
    vector<int> v;
    v.push_back(2);
    v.push_back(1);
    
    Compare c(2);
    FunctionObjectRef<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

result_of实现非常简单,就是什么也不做的模板类:

template<typename F> struct result_of;
当编译器编译这行代码的时候,就能自动推断出ReturnType

FunctionObjectRef<Compare, int> wrapper_c(c);
typedef typename boost::result_of<FunctionObjectType(ElementType)>::type ReturnType;






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics