65,176
社区成员




template <class Type,typename MemberType,MemberType Type::*Member>
struct member_data :public std::unary_function<Type,ElemType&>
{
inline MemberType& operator()(Type& x){
return x.*Member;
}
};
用法:
struct A{ int a,b;};
member_data<A,int,&A::b> getb;
A object;
getb(object) = 0;//返回b的引用。
有没有办法让memdata所需要的模板参数少一些,像这样:
member_data<&A::b> getb;
如果是函数的话是可以的:
template <class Type,typename MemberType>
MemberType& fun(MemberType Type::*Member){
Type x;
return x.*Member;
};
模板类的话应该怎么做呢?
另外如果是函数参数的话呢?(我知道 std::mem_fun();但是它不能被内联,不适合用来做适配器):
template <class Type,typename Result,Result (Type::*pFun)() >
struct member_fun :public std::unary_function<Type,Result>
{
inline Result operator()(Type& x){
return (x.*pFun)();
};
};
菜鸟表示嵌套好复杂
std::for_each( x , x + 3 , [](test& x){ x.func() ; } );
int main()
{
test x[3]={test(1),test(2),test(3)};
std::for_each( x , x + 3 , std::mem_fun_ref(&test::func) );
std::for_each(x,x + 3,my::member_fun<test,void,&test::func>());
system("pause");
return 0;
}
std::for_each( x , x + 3 , std::mem_fun_ref(&test::func) );
008D1047 lea esi,[ebp-10h]
008D104A lea ebx,[ebx]
008D1050 mov ecx,esi
008D1052 call test::func (8D1000h)
008D1057 add esi,4
008D105A lea eax,[ebp-4]
008D105D cmp esi,eax
008D105F jne main+30h (8D1050h)
std::for_each(x,x + 3,my::member_fun<test,void,&test::func>());
008D1061 mov edi,dword ptr [__imp__printf (8D209Ch)]
008D1067 lea esi,[ebp-10h]
008D106A lea ebx,[ebx]
008D1070 mov ecx,dword ptr [esi]
008D1072 push ecx
008D1073 push offset string "%d\n" (8D20F4h)
008D1078 call edi
008D107A add esi,4
008D107D lea edx,[ebp-4]
008D1080 add esp,8
008D1083 cmp esi,edx
008D1085 jne main+50h (8D1070h)
#include<stdio.h>
#include<functional>
#include<algorithm>
class test
{
int m;
public:
test( int x ):m(x)
{
}
void func()
{
m;
printf("%d\n",m);
}
};
int main()
{
test x[3]={test(1),test(2),test(3)};
std::for_each( x , x + 3 , std::mem_fun_ref(&test::func) );
return 0;
}
PUBLIC _main
; Function compile flags: /Ogtpy
; File c:\documents and settings\hwp\桌面\test.cpp
; COMDAT _main
_TEXT SEGMENT
_x$ = -12 ; size = 12
_main PROC ; COMDAT
; 22 : {
sub esp, 12 ; 0000000cH
push esi
; 23 :
; 24 : test x[3]={test(1),test(2),test(3)};
mov DWORD PTR _x$[esp+16], 1
mov DWORD PTR _x$[esp+20], 2
mov DWORD PTR _x$[esp+24], 3
; 25 :
; 26 : std::for_each( x , x + 3 , std::mem_fun_ref(&test::func) );
lea esi, DWORD PTR _x$[esp+16]
$LL15@main:
mov ecx, esi
call ?func@test@@QAEXXZ ; test::func
add esi, 4
lea eax, DWORD PTR _x$[esp+28]
cmp esi, eax
jne SHORT $LL15@main
; 27 :
; 28 :
; 29 : return 0;
xor eax, eax
pop esi
; 30 : }
add esp, 12 ; 0000000cH
ret 0
_main ENDP
_TEXT ENDS
END