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

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.

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

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);

std::mem_fun vs std::mem_fn

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.

What is the simplest way to "cast" a member function pointer to a function pointer in C++?

I want to provide a member function for the "comp" parameter of an STL algorithm like lower_bound( ..., Compare comp ). The comp() function accesses a non-static member field so it must itself be a non-static member but the type of a non-static member function pointer is different from that of an ordinary function pointer.
What is the best way around this problem?
This is the most common use of std::mem_fun and std::mem_fun_ref. They're templates that create functors that invoke the specified member function. TR1 adds an std::tr1::bind that's also useful and more versatile (and if you don't have TR1 available, that's based on Boost::bind). C++0x will include std::bind in the standard library (virtually unchanged from TR1).
It sounds like you want something like boost::bind, to bind the member function pointer to a instance of that class.
Would you care to elaborate your question a bit as to what you're trying to do? Example code, etc.?
#include<tr1/functional>
and use mem_fn()

boost::bind accessors?

Suppose I have the following code:
int f(int, int);
int main()
{
SomeFunc(boost::bind(f, 1, 2));
}
From the SomeFunc() function, is it possible to access the arguments held by the bound type? Something like this (pseudo code):
// Obvious syntax issues...
void SomeFunc(boost::bind& functor)
{
if(functor.function == &f)
{
if(functor.argument1 == 1)
DoSomething();
}
}
Can I pull this information out of the boost::bind type?
boost::bind is a templated function, not a type. The real type returned by that function is some kind of functor of an unspecified type. As a matter of fact, it probably returns many different unspecified types depending on what the arguments to the boost::bind function are.
As the type is unspecified and the library only states that is CopyConstructible, that implements operator() with the appropriate number and type of arguments (one for each placeholder, types deduced from the bound method/function) and that it offers an inner type result_type that is the same as the return type of that operator().
The interface of those unspecified classes is, well, unspecified. It will probably not offer accessors to the arguments, and even if it does, and you get inside knowledge from studying the internals of the library, you risk having your code break with upgrades to the library (the implementor is free to change the type and all the interface that is not publicly documented).
The whole library is built around the fact that you do not really care about what the arguments are or even if any argument is defined or only placeholders are used, you only care that the resulting object will be callable with a given interface.
So no, you cannot.
The real question is why would you want to do that?
I suspect you can't but the fact that you are trying is a bit worrying.
No, you cannot do that with boost::bind.
boost::bind just generates a sort of functor object where all details are hidden. Than you construct boost::function or boost::signal with it and the only thing you can do: execute. You even cannot compare boost::function objects.
Anyway, it is not clear that the problem you are solving. Such approach looks awkward to me. Are you sure you really need that?