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