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;
        }
    };
  • 相关阅读:
    Ubuntu 网络代理配置
    WSL2 环境配置
    两台笔记本电脑实现同一wifi下虚拟主机网络实现互通
    Linux /dev/loop0文件详解
    Excel两张表查重,返回True
    计算机网络基础/进制转换/企业级子网IP划分
    leetcode 2030. 含特定字母的最小子序列
    nginx https
    kubernetes(二十四)ingress https
    求两个向量的旋转矩阵 E
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11574279.html
Copyright © 2011-2022 走看看