std::bind用来将可调用对象与其参数一起进行绑定。绑定后的结果可以使用std::function进行保存,并延迟调用到任何我们需要的时候。通俗来说,它主要有两个作用:
1.将可调用对象与其参数一起绑定成一个仿函数。
2.将多元(参数个数为n,n > 1)可调用对象转换为一元或者(n -1)元可调用对象,即只绑定部分参数。
绑定器函数使用语法格式如下:
//绑定非类成员函数/变量
auto f = std::bind(可调用对象地址,绑定的参数 / 占位符);
//绑定类成员函数/变量
auto f = std::bind(类函数 / 成员地址,类实例对象地址,绑定的参数 / 占位符);
代码如下:
#include <iostream>
#include <functional>
using namespace std;void output(int x, int y)
{cout << x << " " << y << endl;
}int main()
{bind(output, 1, 2)();bind(output, placeholders::_1, 2)(10);bind(output, 2, placeholders::_1)(10);//bind(output, 2, placeholders::_2)(10);//error,调用时没有第二个参数bind(output, 2, placeholders::_2)(10, 20);bind(output, placeholders::_1, placeholders::_2)(10, 20);bind(output, placeholders::_2, placeholders::_1)(10, 20);return 0;
}
测试结果:
可调用对象绑定器的使用:
代码如下:
#include <iostream>
#include <functional>
using namespace std;void testFunc(int x, int y, const function<void(int, int)> &f)
{if (x % 2 == 0){f(x, y);}
}void output_add(int x, int y)
{cout << "x = " << x << ", y = " << y << ",x+y = " << x + y << endl;
}int main()
{for (int i = 0; i < 10; i++){auto f = bind(output_add, i + 100, i + 200);testFunc(i, i, f);auto f1 = bind(output_add, placeholders::_1, placeholders::_2);testFunc(i, i, f1);}return 0;
}
测试结果:
代码如下:
#include <iostream>
#include <functional>
using namespace std;class Test
{
public:void output(int x, int y){cout << "x = " << x << " " << "y = " << y << endl;}int m_number = 100;
};int main()
{//成员函数绑定Test t;auto f2 = bind(&Test::output, &t, 520, placeholders::_1);f2(1314);//成员变量绑定auto f3 = bind(&Test::m_number, &t);cout << f3() << endl;f3() = 666;cout << f3() << endl;return 0;
}
测试结果:
可调用对象包装器的使用:
代码如下:
#include <iostream>
#include <functional>
using namespace std;class Test
{
public:void output(int x, int y){cout << "x = " << x << " " << "y = " << y << endl;}int m_number = 100;
};int main()
{//成员函数绑定Test t;auto f2 = bind(&Test::output, &t, 520, placeholders::_1);f2(1314);function<void (int,int)> f22 = bind(&Test::output, &t, 520, placeholders::_1);//成员变量绑定auto f3 = bind(&Test::m_number, &t);function<int&(void )> f33= bind(&Test::m_number, &t);cout << f3() << endl;f3() = 666;cout << f3() << endl;return 0;
}