Home > Software design >  What is the advantage of using boost::bind?
What is the advantage of using boost::bind?

Time:09-17

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related