Why does std::function accept a this reference in the signature?
c++, function, this
Solution
`std::function<SIG>` can be constructed from many things that behave like functions, converting them to an appropriate `std::function` object.
In this case `void S::foo()` behaves much like a function `void foo_x(S&)` (as in they both require an `S` to call, and potentially modify `S`, returning nothing). Consequently `std::function<void(S&)>` provides a constructor for converting the 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::)() )`, to create something equivalent to:
void foo_x(S & s ) { return s.foo(); }
std::function<void(S&)> func = foo_x;
Similarly,
std::function<void(S * const)> func = &S::foo;
is equivalent to
void foo_x(S * const s ) { return s->foo(); }
std::function<void(S* const )> func = foo_x;
through a constructor like `std::function<void(S* const )>( void(S::)() )`.
Problem
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?