1

Hello I have this text from C++ Primer 5th edition:

function<bool (const string&)> fcn = &string::empty; find_if(svec.begin(), svec.end(), fcn);

Here we tell function that empty is a function that can be called with a string and returns a bool. Ordinarily, the object on which a member function executes is passed to the implicit this parameter. When we want to use function to generate a callable for a member function, we have to “translate” the code to make that implicit parameter explicit.

So what he meant with: "When we want to use function... make that implicit parameter explicit"?

1 Answer 1

4

It refers to the implicit this parameter to member functions. They get a pointer to the current object passed under the hood. std::function has some magic to turn that implicit parameter into an explicit one:

#include <iostream> #include <functional> struct foo { void bar() { std::cout << "Hello World\n";} }; int main() { std::function< void (foo&)> g = &foo::bar; foo f; f.bar(); // bar takes no parameters, but implicitly it gets a pointer to f g(f); // g(f) explicitly gets the parameter } 

With f.bar() its the method call syntax that tells us that we call bar on the object f. f can be said to be an implicit parameter to bar. With g(f) that parameter is passed explicitly.


PS: Of course it isn't "magic", but I understood the question is about the general meaning of the implicit parameter, while explaining how std::function turns member functions into free callables is perhaps a topic for a different question.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! You made it clear for me through such useul and easy explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.