大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
函数对象是重载了()操作符的类。
template<typename T>
class FunObj
{
public:
    
void operator()(T, T) const
    
{
        cout
<<"call"<<endl;
    }

}
;

int main()
{
    FunObj
<int> fi;
    fi(
4,5);
    
return 0;
}

与一般函数相比,有以下优点:
1、因为是一个类,所以可以利用成员变量保存状态。
2、如果是一个模板类,可以实现不同的参数类型。
3、利用模板非类型参数编译期被求值的特性,可以进行优化。
4、与函数指针相比,可以进行内联。


STL中的函数对象
//自定义的函数对象
template<typename T>
class FunObj
{
public:
    
bool operator()(T, T) const
    
{
        cout
<<"call"<<endl;
        
return false;
    }

}
;

//自定义的函数模板
template<typename T>
bool Fun(T,T)
{
    
return false;
}



int main()
{
    vector
<int> vi(6);
    sort(vi.begin(), vi.end(), greater
<int>());        //预定义的函数对象
    sort(vi.begin(), vi.end(), FunObj<int>());        //自定义的函数对象
    sort(vi.begin(), vi.end(), Fun<int>);            //自定义的函数指针
    return 0;
}


预定义的三种函数对象
    //预定义的算术函数对象
    cout<<    plus<int>()(5,6)        <<endl;
    cout
<<    minus<int>()(6,5)        <<endl;
    cout
<<    multiplies<int>()(5,6)    <<endl;
    cout
<<    divides<int>()(12,6)    <<endl;
    cout
<<    modulus<int>()(13,6)    <<endl;
    cout
<<    negate<int>()(12)        <<endl;

    
//预定义的关系函数对象
    cout<<boolalpha<<    equal_to<int>()(12,13)        <<endl;
    cout
<<boolalpha<<    not_equal_to<int>()(12,13)    <<endl;
    cout
<<boolalpha<<    greater<int>()(12,13)        <<endl;
    cout
<<boolalpha<<    less<int>()(12,13)            <<endl;
    cout
<<boolalpha<<    greater_equal<int>()(12,13)    <<endl;
    cout
<<boolalpha<<    less_equal<int>()(12,13)    <<endl;

    
//预定义的逻辑函数对象
    cout<<boolalpha<<    logical_and<int>()(12,13)    <<endl;
    cout
<<boolalpha<<    logical_or<int>()(12,13)    <<endl;
    cout
<<boolalpha<<    logical_not<int>()(12)        <<endl;

函数对象适配器
    //绑定器,将二元函数对象转换成一元函数对象
    cout<<boolalpha<<    bind2nd(less<int>(),5)(6)    <<endl;        //第二个值绑定
    cout<<boolalpha<<    bind1st(less<int>(),5)(6)    <<endl;        //第一个值绑定
    
    
//取反器,将函数对象结果取反
    cout<<boolalpha<<    not2(less<int>())(2,3)            <<endl;    //二元
    cout<<boolalpha<<    not1(bind2nd(less<int>(),5))(2)    <<endl;    //一元

posted on 2009-06-22 10:23 大胖 阅读(168) 评论(0)  编辑 收藏 引用 所属分类: STL

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理