STL源码剖析学习十八:仿函数

仿函数
又叫函数对象,可以达到“将整组操作当做算法的参数”,定义于头文件<functional>
STL仿函数应该具有配接的能力

一般写法:

template<class T>
class A
{
    public:
    operator()(T x)const
    {
        //operations
    }
    private:
    //
}

调用方式
A<int>()

 

用class和struct都可以,注意class中必须要将重载()的函数写在public内

STL不支持三元仿函数
定义两个class,分别代表一元仿函数和二元仿函数

template<class Arg, class Result>
struct unary_function
{
    typedef Arg argument_type;
    typedef Result result_type;
}

template<class Arg1, class Arg2, class Result>
struct binary_function
{
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
}

 


加法的仿函数:

template<class T>
struct plus: public binary_fuction<T, T, T>
{
    T operator()(const T& x, const T& y) const
    {
        return x+y;
    }
}

 

 

证同:
将其参数原封不动的传回,其中一些对其传回的参数有刻意的选择
为了间接性,为了抽象化而设计的间接层

template<class T>
struct identity : public unary_function<T, T>
{
    const T& operator()(const T& x) const
    {
        return x;
    }
}

 

还有select1st,select2nd返回pair的第一个和第二个元素

posted @ 2012-04-30 21:32  w0w0  阅读(208)  评论(0编辑  收藏  举报