2018.7.5 学习内容:bind函数

1、基本概念

bind函数定义在头文件 functional 中。可以将 bind 函数看作一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。——《C++Primer  5th》

2、bind的参数

  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4. using namespace std::placeholders;
  5. int main(void)
  6. {
  7. void confun(int a, int b, int c);
  8. auto con = bind(confun, 3, _2, _1);
  9. con( 5, 4);
  10. }
  11. void confun(int a,int b,int c)
  12. {
  13. cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << endl;
  14. }
bind接受一个可调用对象 第一个参数就是需要改变参数的可调用对象。 confun原来需要三个参数,经bind修改后 只需要传入两个参数,便可通过con调用confun函数。

_2 ,_1 为占位符,在(3)中详解。这里需要知道的是bind可以改变一个可调用对象的参数列表生成一个新的可调用对象去被调用。

3、用bind重排参数顺序

  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4. using namespace std::placeholders;
  5. int main(void)
  6. {
  7. void confun(int a, int b, int c);
  8. auto con = bind(confun, 3, _2, _1);
  9. con( 5, 4);
  10. }
  11. void confun(int a,int b,int c)
  12. {
  13. cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << endl;
  14. }
上述程序执行后会输出   a=3 b=4 c=5

你会发现调用con时传入的顺序是  5,4    但是输出结果却是 b=4 c=5 。这就是占位符的作用,_2接受con的第二个参数4,_1接受con的第一个参数 。3, _2,_1又对应的是confun的a,b,c 所以 a=3,b=4,c=5.

如果还不清楚,再看下面这个例子

  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4. using namespace std::placeholders;
  5. int main(void)
  6. {
  7. void confun(int a, int b, int c,int d);
  8. auto con = bind(confun,_2, 4,_1,_3);
  9. con( 5, 6, 3);
  10. }
  11. void confun(int a,int b,int c,int d)
  12. {
  13. cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << ends << "d=" << d << endl;
  14. }
输出结果为 a=6 b=4 c=5 d=3

confun参数a  对应占位符 _2接受con第二个参数 6 ,b对应4,c对应占位符_1接受con第一个参数 5 ,d对应占位符_3,接受con第三个参数3

4、绑定引用参数

默认情况下,bind的那些不是占位符的参数被拷贝到bind返回的可调用对象中。但是,与lambda类似,有时对有些绑定的参数我们希望以引用方式传递,或是要绑定参数的类型无法拷贝,可以用ref(参数)

小细节:

class A
{
public:
    int Func(int x, int y)
    {
        return x + y;
    }
};
int main()
{
    A a;
    //bf2把一个类成员函数绑定了类对象,生成了一个像普通函数一样的新的可调用实体
    auto bf2 = std::bind(&A::Func, a, std::placeholders::_1, std::placeholders::_2);     
    cout << bf2(10, 20);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42022726/article/details/80930762