cpp::daily #Episode002 - std::bind and std::placeholders, 10 examples!
std::bind and std::placeholders, 10 examples!
We often need to implement a function on demand, that is, pass parameters according to the needs of our application. And
std::placeholders are for that.
std::placeholders namespace works together with the
std::bind function and we need to include the
<functional> header in order to use it. They contain placeholder objects [
_1, ..._ N] where N is a maximum number defined by the implementation.
The std::bind function template returns a function object based on fn, but with its arguments linked to args.
When used as an argument in a
std::bind expression, placeholder objects are stored in the generated function object and when that function object is called with unbound arguments, each
_N placeholder is replaced with the corresponding umpteenth unbound argument .
Connections characteristics and placeholders
- Each placeholder is declared as:
extern / * not specified * / _1; // up to c ++ 17;
- Implementations are encouraged to declare placeholders as:
inline constexpr / * unspecified * / _1;
- Although I declare them by:
extern / * unspecified * / _1; , is still allowed by the standard;
- The types of placeholder objects are DefaultConstructible and CopyConstructible
- Your standard copy/move builders do not throw exceptions;
- For any
- It is defined and derived from
01. Using the basics with parameter
Given the function
sum_sub(int, int, int) which returns the sum and subtraction of the parameters, respectively, if we want a parameter to be dynamic:
- Third dynamic parameter
02. Second dynamic parameter
03. First dynamic parameter
04. Substituting 2 parameters
_2. As we are using parameter
_2, we need to pass 2 parameters, otherwise it generates an error when compiling.
05. Substituting 2 parameters with change in order
06. Substituting 2 parameters, but changing only the second
_2 = y,
x = 1,
z = 3. You have to pass 2 parameters (otherwise, don’t compile), but the first one will be ignored!
07. Replacing only the 3rd parameter
To understand once and for all!
x = _3, you need to enter 3 parameters (otherwise it does not compile), because you are using
_3, but the first two will be ignored.
08. Using alias
New name function:
show_name( std::string & )
09. Without using the
10. Without indicating
Trivia: If you use pure
std::bind, it may give you an incorrect result. Another thing is also if you use lib boost bind:
boost::bindis not compatible with