Miscellaneous: Function / Bind

code

Syntax

std::function is a wrapper to a simple function, to a functor or to a lambda expression.
std::bind is a template function that returns a std::function object that binds a set of arguments to a function.

 

bind returns a new function object with a different prototype because some or all the parameters of the function were already specified.

 

We can specify only some parameters (not all), and to do so we need to use placeholders for the rest.

These placeholders are in the header file <functional> under namespace ::placeholders.

In the code below, we have a function with 2 parameters, and i want to bind only one of them. The second parameter (that we will leave unchanged) is marked as placeholder (starting from 1). The new function will have the first parameter binded to 5, while the second one will be dynamic. This means that the new function will receive only one parameter.

PROS

  • Function acts as a wrapper to all the possible function declarations
  • Bind binds parameters to a given function, creating a new one that have those params pre-set.

CONS

  • The bind function becomes harder to read, especially if the parameter places are switched

 

The position of the placeholder can be changed, doesn’t have to be in order.

 

Leave a comment

Your email address will not be published.