bind () 函数简介
std::bind()函数作为函数的适配器,它可以扩大函数是使用场合,使得函数更加灵活的被使用。
std::bind
生成一个函数对象,我们称为std::bind
返回的函数为绑定对象(bind object)。std::bind
的第一个实参是一个可调用对象,接下来的所有实参表示传给改对象的值。
template<class F, class… Args>
bind(F&&f, Args&&… args);
参数:
f 可以是function object,函数指针,函数引用,成员函数指针,或者static数据成员的指针。
返回值:
function object
bind 简单使用–普通函数
placeholders 命名空间下的_1, _2, _3 指示函数参数数量和位置。
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
void func(int a, int b, int c)
{
cout << (a -b -c) << endl;
}
int main(int argc, char *argv[])
{
auto fn1 = bind(func, _1, 2, 3);
auto fn2 = bind(func, 2, _1, 3);
fn1(10);
fn2(10);
return 0;
}
// 结果
5
-11
bind 类静态函数和成员函数
普通函数和类的static函数可以隐式转换为函数指针,不需要加&,不传类的对象进去。
类的成员函数不能隐式转换为函数指针,需要显示加&,且需要将类名传递,但类对象可以加可以不加&。
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
class test_callback
{
public:
test_callback(void):a(10),b(100){ }
typedef function<void(int,int)> callback;
void use_value(callback func) {
cout << "value a is " << a << endl;
cout << "value b is " << b << endl;
func(a, b);
}
private:
int a;
int b;
};
class client
{
public:
client(){ this->value = 2; }
static void print_sum(int a, int b, int c) {
cout << a + b +c << endl;
}
void print_multiply(int a, int b, int c, int d) {
cout << a * b * c * d << endl;
cout << "client value is " << this->value << endl;
}
private:
int value;
};
int main(int argc, char *argv[])
{
test_callback test1;
client client1;
// 普通函数和类的static函数可以隐式转换为函数指针,不需要加&
test1.use_value(bind(client::print_sum, _2, _1, 0));
// 类的成员函数不能隐式转换为函数指针,需要显示加&,且需要将类名传递,但类可以加可以不加&
test1.use_value(bind(&client::print_multiply, &client1, _1, _2, 2, 3));
test1.use_value(bind(&client::print_multiply, client1, _1, _2, 2, 3));
return 0;
}
// 结果
value a is 10
value b is 100
110
value a is 10
value b is 100
6000
client value is 2
value a is 10
value b is 100
6000
client value is 2