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()函数

  • 相关阅读:
    MSSQL 跨数据库连接
    powerdesigner逆向工程,从数据库导出PDM
    JS面向对象的程序设计
    数据脚本
    JDK安装与环境变量配置
    sql: 去除数据库表中tab、空格、回车符等特殊字符的解决方法
    用SQL语句获得一个存储过程返回的表
    百度云下载速度慢解决方法
    【WCF全析(一)】--服务协定及消息模式
    【WCF全析(二)】--服务配置部署详解
  • 原文地址:https://www.cnblogs.com/cutepig/p/1400359.html
Copyright © 2011-2022 走看看