zoukankan      html  css  js  c++  java
  • STL源码剖析:仿函数

    • 仿函数就是函数对象

    • 函数对象:

      • 重载了operator()的类对象

      • 使用起来和普通函数一致,所以称为函数对象或是仿函数

    • STL中对于仿函数的参数进行了特殊处理,定义了两个特殊类,类里面只有类型定义

      • 一元函数类,unary_function

    template <class Arg, class Result>
    struct unary_function
    {
        typedef Arg argument_type;
        typedef Result result_type;
    };
      • 二元函数类,binary_function
    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_function<T, T, T>
    {
        T operator()(const T& x, const T& y)
        {
            return x + y;
        }
    }
    • 证同
      • 任何人数值使用证同函数后,得到的都是自己

    template <class T>
    struct identity :public : public unary_function<T, T>
    {
        T& operator()(const T& x) const
        {
            return x;
        }
    }
    • 选择函数
      • 接收一个pair,返回first或second元素

    template <class Pair>
    struct select1st : public unary_function<Pair, typedef pair::first_type>
    {
        const typename Pair::first_type& operator()(const Pair& x) const
        {
            return x.first;
        }
    }
    
    template <class Pair>
    struct select2nd : public unary_function<Pair, typedef pair::second_type>
    {
        const typename Pair::second_type& operator()(const Pair& x) const
        {
            return x.second;
        }
    };
    • 投射函数
      • 返回第一或是第二个参数

    template <class Arg1, class Arg2>
    struct project1st : public binary_function<Arg1, Arg2, Arg1>
    {
        Arg1 operator()(const Arg1& x, const Arg2&) const
        {
            return x;
        }
    };
    
    template <class Arg1, class Arg2>
    struct project2nd : public binary_function<Arg1, Arg2, Arg2>
    {
        Arg2 operator()(const Arg1&, const Arg2& y) const
        {
            return y;
        }
    };
  • 相关阅读:
    多层开发的小知识
    DIV+CSS基础教程:导航条的制作详解
    JavaScript函数
    css:学习CSS了解单位em和px的区别
    blank开新窗口为什么通不过W3C验证
    对javascript匿名函数的理解(透彻版)
    .net如何与windows身份验证的sql数据库连接
    Aptana2.0系列教程
    C# Tostring() 格式大全
    类关系图
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11574279.html
Copyright © 2011-2022 走看看