What is the bind function

Previously introduced lambda expressions, lambda expressions are written in each invocation of a small function, that is, write to use, cannot be used repeatedly, the advantage is not to break the original integrity of the code. But if we’re going to call a function over and over again, we’ll use bind.

The bind function is used to bind some form of argument list to a known function to form a new function. This practice of changing an existing function call pattern is called function binding. Bind functions as a function adapter, modifying existing functions to produce new ones.

Method of use

Header file: <funtional>

Format: auto fun = bind(functionName, arg_list) // The preceding type must be auto

When a function is called, arg_list is the argument list, and when a function is called by bind, it uses the placehoders placeholder, whose header is also funtional, so that the namespace of a placeholder is STD ::placeholder

#include <iostream>
#include <functional>
void fun(int a,int b)
{
    std::cout<<a<<""<<b<<std::endl;
}
int main()
{
    auto f1 = bind(fun,std::placeholders::_1,std::placeholders::_2); // Call f1 with two arguments auto f2 =bind(fun,5,std::placeholders::_1); // F2 is passed as the second parameter of fun, the first parameter being the fixed parameter 5 auto f3 =bind(fun,5,std::placeholders::_2); F1 (3, 2); //cout:3 2 f2(3); //cout:5 2 }Copy the code

Placeholder when the placeholder is 3,2, placeholder f1 when fun is used, placeholder when the placeholder is 3,2, placeholder when bind is returned Alternatively, you can replace these placeholders with fixed values, which will be passed to Fun in the same order.

By value

By default, arguments to bind are passed by value, that is, copy values.

If you want to pass references, you use the library ref function, which returns a copy-able object containing a reference to the original object. There is no change in the way the value is passed, it is still passed because ordinary references cannot be copied. So the object returned by ref encapsulates a reference, which is of type Reference_wrapper.

Alternatively, the CREf function returns a reference_wrapper object with a const reference so that the function cannot change its value (the benefit is to avoid copying the original object).