Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::function accept a this reference in the signature?

Tags:

c++

function

this

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?

like image 571
chris Avatar asked Sep 21 '12 03:09

chris


People also ask

Why did we need to use an std :: function object?

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.

What is the type of std :: function?

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'.


1 Answers

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.

like image 163
Benjamin Lindley Avatar answered Nov 14 '22 22:11

Benjamin Lindley