简体   繁体   中英

why can get address of member function by class type

I met this code:

 auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);

in the previous code, we can apply the address operator to a member function while there is no instance object been created, how can that be possible?

The type system of C++ contains a lesser-known category of types which are pointers to members . Given any class type C and any object or function type T , there is a pointer-to-member type TC::* . Values of these types can be obtained by applying the address-of operator to the qualified name of a class member. For example:

 struct Foo;

 int Foo::* pi;                  // C = Foo, T = int
 void (Foo::* pf)(bool, int);    // C = Foo, T = void(bool, int)

 struct Foo {
     int a;
     int b;
     void f(bool, int);
     void g(bool, int);
 };

 pi = &Foo::a;
 pf = &Foo::f;

The member pointer itself only selects a class member abstractly, unrelated to any class instance . To actually use the pointer, you need a class instance, and the member-dereference operator .* :

Foo x;

int n = x.*pi;     // gets x.a
(x.*pf)(true, n);  // calls x.f(true, n)

pf = &Foo::g;
(x.*pf)(true, n);  // calls x.g(true, n)

(The parentheses in the call expression through the pointer-to-member pf are necessary because otherwise the expression a.*b(c) means a.*(b(c)) . This is occasionally a point of confusion for new users.)

Don't confuse a pointer-to-member to an object member with a pointer to the actual object!

int * p = &(x.*pi);   // p = &x.a

Here p points to the actual int subobject xa and is an ordinary object pointer, whereas pi is a pointer-to-member that abstractly selects the Foo::a member of a Foo object.

Taking the address of Foo 's member function gives you a pointer to member function. This type is completely independent of any Foo object. If you're going to actually call the function, you need to provide a Foo object. In this case, the this parameter of Foo::print_sum is being bound to &foo with std::bind .

当然,您需要具有名为foo Foo类型的实例,因为成员函数Foo::print_sum绑定到foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM