std::mem_fun vs std::mem_fn - c++

What is the difference between std::mem_fun and std::mem_fn? Why is the naming so confusing?
Boost's documentation says that std::mem_fn can replace std::mem_fun in most cases. So in what situation would you still use std::mem_fun?

std::mem_fun is deprecated. std::mem_fn can do everything it does, and it does it more conveniently. The relation between the two is the same as the relation between std::bind1st/std::bind2nd and the C++11 std::bind. Both std::mem_fn and std::bind were developed and mastered after std::bind1st and std::mem_fun were made into the C++98 Standard. So that means we had to wait until C++11 to properly replace the old stuff with the superior alternatives.
For instance, std::mem_fun can only deal with member functions that take one or no argument. std::mem_fn is variadic and can deal with members that take any number of arguments.
You also need to pick between std::mem_fun and std::mem_fun_ref depending on whether you want to deal with pointers or references for the class object (respectively). std::mem_fn alone can deal with either, and even provides support for smart pointers.
The documentation of boost::mem_fn explains when to use std::mem_fun, and put simply that's when you need to operate with code that expects std::mem_fun, or that expects adaptable functors (which is an obsolete notion* from C++03). For those cases you wouldn't be able to plug in std::mem_fn either, so there you have it: you would use std::mem_fun for legacy.
*: I mean by that that new code shouldn't rely on the C++03 protocol of having e.g. result_type member types (it's more customary to use the new traits like std::result_of) -- the new facilities like std::bind/std::mem_fn do in fact provide those members if they would have been present in equivalent C++03 code. I leave it to you to figure out whether you should update old code that relies on adaptable functors with std::mem_fn by relying on this behaviour.

Related

What is the advantage of using boost::bind?

The definition and application of boost::bind are clearly outlined in the boost website, yet I hardly could find what is the benefit of using it over using a normal function call? Or to put it simply in which scenarios it might come in handy?
Sometimes you have a set of arguments that you are going to pass to the function, but you wish to call the function later without needing to pass the arguments that are already known. One reason to need this may be because the call may need to conform to an interface that doesn't allow those arguments. This is typical in the (functor style) "callback" idiom.
That situation can be solved by defining a class that stores the arguments as members, and defines function call operator overload that delegates to the original function and passes the arguments stored as members.
boost::bind is a structured way to represent such "argument binding" without needing to define the class yourself. The standard library used to have std::bind1st and std::bind2nd which were more limited, less generic forms of bind.
boost::bind is rarely needed anymore since it was introduced to the standard library as std::bind in C++11, and furthermore lambdas were introduced in C++11 and improved in C++14 and they have largely obsoleted bind.
bind provides a way to take a function or a function object with a certain arity and transform it to another function with lesser arity by precisely binding one or more arguments. And you can do it in place.
bind and functions don't have a good comparison.
bind is more comparable to simple lambdas that call a function and fix certain parameters in their implementation.
The big difference between boost::bind and a modern lambda is that the bind object has a certain degree of instrospection associated with it that the lambda doesn't have.
For example you could in principle recover the original function and reconstruct what is the argument bound.
In a lambda everything is private, even the simplest implementation.
In other words, the result of boost::bind is an "expression" and the type has well defined pattern (e.g. boost::bind_t<...> or something, and that can be matched in a template function argument).
Lambdas instead are each their own unknowable sui generis type.
Admittedly, few people maybe interested in the difference, but it is there and I played with it once or twice to implement a symbolic system (for derivatives).
I can't say the same about std::bind because the object returned is unspecified by the standard and it could be more difficult to reconstruct the full bind "expression".

When should you ever use functions over functors in C++?

Functors are apparently more efficient since the compiler is more easily able to inline them, and they work much better with parametrization. When should you ever use a plain old function over a functor?
Functions support distributed overriding. Functors do not. You must define all of the overloads of a Functor within itself; you can add new overloads of a function anywhere.
Functions support ADL (argument dependent lookup), permitting overloading in the argument-type associated namespace. Functors do not.
Function pointers are (kind of) a type-erased stateless functor that is a POD, as evidenced by how stateless lambdas convert into it. Such features (POD, stateless, type erasure) are useful.

Why std::function::argument_type has been deprecated?

I've seen on cppreference that std::function::argument_type was deprecated in C++17. What is the reason behind it? And what ISO WG21 paper was proposing that?
The relevant papers are P0005R4 (which is the paper that was voted into the draft standard) and P0090R0 (which is referenced by P0005R4).
Quotes from P0090R0:
Q2. What's wrong with result_type, etc.?
A2. These C++98/03/TR1-era typedefs predated decltype and perfect
forwarding. Previously, generic code had to request information from
function objects before adapting them. Now, manually communicating
that information is unnecessary. decltype supersedes result_type,
because the compiler can simply report what the result of calling a
function object with specific arguments will be. And perfect
forwarding supersedes the argument_type family, since adaptors can
simply take/store/forward arbitrary arguments.
In fact, these typedefs are worse than useless. They're
counterproductive, because many callable objects lack them. Function
pointers and pointers to members have always lacked them. ptr_fun(),
which wrapped function pointers with these typedefs, was recently
removed (see [1] again). Most importantly, lambdas have always lacked
these typedefs, and they are the most important function objects of
all. Generic lambdas are even more incompatible.
What this means is that if a user attempts to write generic code by
using the result_type family of typedefs, their code won't be generic
- it'll fail to handle lambdas, generic lambdas, function pointers, etc.
These typedefs should be removed because they've become actively
harmful to modern code.
The reason those typedefs exist are so things like not1, bind1st and friends, could query the callables passed to them and retrieve the type of the result of invoking the callable, its argument types etc.
To make their use palatable, a lot of support machinery, like unary_function, ptr_fun, mem_fun etc. were also defined. Notice how all of these are limited to adapting callables taking one or two arguments only, so they're rather limited in that sense.
Now that we have decltype that can be used to deduce a callable's return type, variadic templates and perfect forwarding to forward arbitrary number of arguments to functions, etc. the pre-C++11 mechanisms are way too cumbersome to use.
Stephan T Lavavej first proposed getting rid of these in C++17 in p0090r0. Relevant excerpts from the paper:
Q1. What are you proposing?
* Removing every mention of result_type, argument_type, first_argument_type, and second_argument_type ...
* Removing the negators not1() and not2(), which were powered by these
typedefs.
Q2. What's wrong with result_type, etc.?
A2. These C++98/03/TR1-era typedefs predated decltype and perfect forwarding. Previously, generic code had to request information from function objects before adapting them. Now, manually communicating that information is unnecessary. decltype supersedes result_type, because the compiler can simply report what the result of calling a function object with specific arguments will be. And perfect forwarding supersedes the argument_type family, since adaptors can simply take/store/forward arbitrary arguments.
If you search the paper for [func.wrap.func], it talks specifically about removing the std::function typedefs you're asking about.

C++: Creating a function object with mem_fn and bind1st

Disclaimer: This description contains a lot of Qt specific functionality. This is not necessary to answer the question, I'm just including it to explain the background.
I need to do some heavy computations in my QT application.
In order to do this, I would like to use QtConcurrent::run(myFunction) This is Qt's version of async and creates a future, which at some point will contain the result of myFunction.
The problem is that the function is both a member function and takes complex parameters.
I know that you can pass both a function and a pointer to QtConcurrent::run. The function will then be invoked on the pointer. You can even provide a list of parameters. But it seems like this list only accepts parameters such as int, double or QString.
Actual Question:
I would like to convert this line of code:
model->nextStep(simulatedResult->last().molecules, dt)
into
myFunction()
That means I need to
bind the pointer to the function
bind the arguments to the function
This is my code so far:
auto memfun=std::mem_fn(&ConcreteModel::nextStep);
auto memfun_bound_to_model=std::bind1st(memfun,model);
auto memfun_bound_result=std::bind1st(memfun_bound_to_model,simulatedResult->last().molecules);
auto memfun_bound_dt=std::bind1st(memfun_bound_result,dt);
Unfortunately this doesn't work.
There are 18 compiler errors, here is the pastebin: http://pastebin.com/2rBQgFNL
It would be great, if you could explain how to do this properly.
Not necessary for an answer, but even better, would be code for QtConcurrent::run.
Simply use a lambda expression.
auto myFunction = [&] { return model->nextStep(simulatedResult->last().molecules, dt); }
You could also use std::bind (see #JonathanWakely's answer), but lamda expressions are imho more universal and powerful.
Also, keep in mind that reading and writing to the same memory from multiple threads will result in a data race (don't pass pointers/references to mutable data to the QT threads unless synchronization is used).
You're trying to mix the C++98 bind1st with the C++11 mem_fn, which isn't possible.
bind1st requires an adaptable binary function which means one that defines certain typedefs, and one that takes exactly two arguments. You can't use it with something that requires more than two and keep binding one argument at a time.
In C++11 it is possible to wrap function objects without those typedefs, thanks to decltype and other new features, so "adaptable binary function" is a useless concept now, and bind1st is useless and deprecated.
The solution is simply to use C++11 features instead of bind1st, e.g. std::bind or a lambda expression.
auto myFunction = std::bind( &ConcreteModel::nextStep, model, simulatedResult->last().molecules, dt);

Can intermixing std::'s and boost::'s ::bind and ::function cause problems?

I think the answer to this is no, but I just want to be sure.
If I have a std::function as a parameter in a function, is there any problem with passing in a boost::bind and vice-versa?
edit:
I discovered that the placeholders used by boost::bind are imported directly into the namespace when you include boost\bind.h, and they are incompatible with std::bind. For std::bind you have to refer to the placeholders explicit, like so: std::placeholders::_1, or do some other typedef or using magic to make them both available simultaneously.
No. The whole purpose of std:: (and boost::) function is that they can accept any function object which can be called with the correct signature- including lambdas, functors, and the result of any kind of binding. They do not care where your function object came from or what type it is.
You can even bind them to each other, although I'm not really sure why you'd want to.