std::bind and std::placeholder placeholders

1、std::bind

Used to bind the parameters of a function call to solve that we may not always be able to obtain all the parameters of a function call at one time. Through this function, we can bind part of the call parameters to the function in advance to become a new After the parameters are complete, the calling scene is completed.

2、std::placeholders

definition:

namespace placeholders 
{
  extern /* unspecified */ _1;
  extern /* unspecified */ _2;
  extern /* unspecified */ _3;
  // ...
}

Among them, _1, _2, _3 are unspecified digital objects, which are used in the bind of the function. _1 is used to replace the first parameter in the callback function, _2 is used to replace the second parameter in the callback function, and so on.

3. An example of combining std::bind and std::placeholders

#include <functional>
#include <iostream>

int foo(int a, int b, int c) 
{
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
    return a + b + c;
}

int main(int argc, char** argv) 
{
    // 将参数 1,2 绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
    auto bindFoo = std::bind(foo, std::placeholders::_1, 1,2);
    // 这时调用 bindFoo 时,只需要提供第一个参数即可
    std::cout << bindFoo(5) << std::endl;

    return 0;
}

Program stdout:

a = 5, b = 1, c = 2
8

 

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/114763244