zoukankan      html  css  js  c++  java
  • std::mem_fun_ref,mem_fun1_ref分析

    举例

    先上一个例子,看看怎么用它

     1#include <functional>
     2#include <stdio.h>
     3
     4struct A
     5{
     6    A(int n):n_(n)
     7    {
     8    }
     9    
    10    int add(int n)
    11    {
    12        return n+n_;
    13    }
    14    
    15    int test()
    16    {
    17        return n_;
    18    }
    19    
    20    int n_;
    21};
    22
    23void main()
    24{
    25    A a(10);
    26    int n = std::mem_fun_ref(&A::test)(a);
    27    int n2 = std::mem_fun1_ref(&A::add)(a,100);
    28    
    29    printf("%d\n", n);    //10
    30    printf("%d\n", n2);    //110
    31}


    分析

    接着看看functional的源代码,分析是怎么实现的执行std::mem_fun_ref(&A::test)(a)时,首先执行这个函数

    23template<class _Result,
    24    class _Ty> inline
    25    mem_fun_ref_t<_Result, _Ty> mem_fun_ref(_Result (_Ty::*_Pm)())
    26    {    // return a mem_fun_ref_t functor adapter
    27    return (std::mem_fun_ref_t<_Result, _Ty>(_Pm));
    28    }

    会将函数的_Result_Ty_Pm分别模板展开为int, A, test,从而返回一个

    mem_fun_ref_t<_Result=int, _Ty=A>(_Pm=test)的对象,而该对象初始化函数代码如下

    template<class _Result,
     3    class _Ty>
     4    class mem_fun_ref_t
     5        : public unary_function<_Ty, _Result>
     6    {    // functor adapter (*left.*pfunc)(), non-const *pfunc
     7public:
     8    explicit mem_fun_ref_t(_Result (_Ty::*_Pm)())
     9        : _Pmemfun(_Pm)
    10        {    // construct from pointer
    11        }
    12
    18private:
    19    _Result (_Ty::*_Pmemfun)();    // the member function pointer
    20    };

    在初始化函数中将成员变量_Pmemfun展开为

    int (A::* _Pmemfun)()

    并初始化为_Pmemfun = &test

    std::mem_fun_ref(&A::test)(a)会执行operator (A & _left)操作

     4    class mem_fun_ref_t

           。。。。。

    13    _Result operator()(_Ty& _Left) const
    14        {    // call function
    15        return ((_Left.*_Pmemfun)());
    16        }

    ,实际上是执行了 _left->_Pmemfun()函数

  • 相关阅读:
    自己常用网站记录
    css弹性布局指定显示行数多余文字去掉用省略号代替以及弹性布局中css 卡片阴影效果
    微信小程序页面传参被截取问题
    阴影效果 css3 为什么要加 -moz-box-shadow -webkit-box-shadow -o-box-shadow,直接用box-shadow不是都能识别吗?
    css常用清除浮动方式
    什么是微信小程序云开发 它的作用是什么
    JMeter压测“java.net.SocketException: Socket closed”解决方法
    Jmeter压力测试工具安装及使用教程
    OnActionExecuting和OnActionExecuted执行顺序
    C#循环下载多个文件(把多个文件压缩成一个文件可以一次性下载)
  • 原文地址:https://www.cnblogs.com/cutepig/p/1400359.html
Copyright © 2011-2022 走看看