Why does std :: function accept this link in the signature?

Member functions have an implicit pointer parameter this . Why does std::function accept this signature, and then where S is a simple class? ( full sample )

 std::function<void(S &)> func = &S::foo; 

The call also works and allocates objects:

 S s1 = {5}; S s2 = {6}; func(s1); //prints 5 func(s2); //prints 6 

What I usually expect is that it needs a pointer that also works: ( full sample )

 std::function<void(S * const)> func = &S::foo; S s1 = {5}; S s2 = {6}; func(&s1); //prints 5 func(&s2); //prints 6 

Why does the first one work when I pass the link to a member function when the implicit this parameter is a pointer?

+7
source share
2 answers

std::function<SIG> can be built from many things that behave like functions, converting them to the corresponding std::function object.

In this case, void S::foo() behaves in the same way as the function void foo_x(S&) (since both of them require a call to S and it is possible to change S without returning anything). Therefore, std::function<void(S&)> provides a constructor for converting a member function into a function object. I.e.

 std::function<void(S &)> func = &S::foo; 

uses a constructor, something like std::function<void(S&)>( void(S::)() ) :) std::function<void(S&)>( void(S::)() ) , to create something equivalent:

 void foo_x(S & s ) { return s.foo(); } std::function<void(S&)> func = foo_x; 

Similarly

 std::function<void(S * const)> func = &S::foo; 

equivalently

 void foo_x(S * const s ) { return s->foo(); } std::function<void(S* const )> func = foo_x; 

through a constructor of the type std::function<void(S* const )>( void(S::)() ) .

+3
source

Because std::function correctly designed. The fact that this is a pointer is an accident of history and an internal part of a member function. This fact should not affect the design decisions of users of the function.

The designers of std::function decided, rightfully, to accept member functions when the first type of parameter in the signature is a link.

+5
source

All Articles