Member functions have an implicit this pointer parameter. Why does std::function accept this signature, then, where S is a simple class? (complete sample)
std::function<void(S &)> func = &S::foo;
Calling it works, too, and distinguishes objects:
S s1 = {5};
S s2 = {6};
func(s1); //prints 5
func(s2); //prints 6
What I’d normally expect is that it needs a pointer, which works as well: (complete 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 a reference into the member function when the implicit this parameter is a pointer?
std::function<SIG>can be constructed from many things that behave like functions, converting them to an appropriatestd::functionobject.In this case
void S::foo()behaves much like a functionvoid foo_x(S&)(as in they both require anSto call, and potentially modifyS, returning nothing). Consequentlystd::function<void(S&)>provides a constructor for converting the member function into a function object. I.e.uses a constructor, something like
std::function<void(S&)>( void(S::)() ), to create something equivalent to:Similarly,
is equivalent to
through a constructor like
std::function<void(S* const )>( void(S::)() ).