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?
It lets you store function pointers, lambdas, or classes with operator() . It will do conversion of compatible types (so std::function<double(double)> will take int(int) callable things) but that is secondary to its primary purpose.
std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them. For std::function , the primary1 operations are copy/move, destruction, and 'invocation' with operator() -- the 'function like call operator'.
Because std::function
is correctly designed. The fact that this
is a pointer is an accident of history and a detail internal to the member function. The fact should have no impact on the design decisions of users of the function.
The designers of std::function
decided, rightly, to accept member functions when the first parameter type in the signature is a reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With