std::bind
是我在实现将类成员函数传递给其他类的回调函数的时候用到的,其能将this指针一并传递,极其方便地解决了该类成员函数作为回调函数时,访问原来类对象中成员变量的问题。
这里对std::bind
进行一个学习记录和总结。
概念
std::bind
可以看作一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来适应原对象的参数列表。
std::bind
将可调用对象与其参数一起进行绑定,绑定后的结果可以使用std::function保存。std::bind
主要有以下两个作用:
- 将可调用对象和其参数绑定成一个仿函数;
- 只绑定部分参数,减少可调用对象传入的参数。
函数原型
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
template< class R, class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
-
f
:一个可调用对象(可以是函数对象、函数指针、函数引用、成员函数指针、数据成员指针),它的参数将被绑定到args
上。 -
args
:绑定参数列表,参数会被值或占位符替换,其长度必须与f
接收的参数个数一致。 -
return
:std::bind
的返回类型是一个未指定类型T的函数对象(所以可以用std::function接收),这个类型T满足以下条件:std::is_bind_expression<T>::value == true
。
调用形式
auto newCallable = bind(callable, arg_list);
- 该形式表达的意思是:当调用
newCallable
时,会调用callable
,并传给它arg_list
中的参数
代码示例
#include <iostream>
#include <functional>
using namespace std;
void func1(int x, int y)
{
cout << "in func1: ";
cout << "x = " << x << ", y = " << y << endl;
}
void func2(int &a, int &b)
{
++a;
++b;
cout << "in func2: ";
cout << "a = " << a << ", b = " << b << endl;
}
class A
{
public:
void func3(int a, int b)
{
cout << "m_name : " << m_name << endl;
cout << " a = " << a << ", b = " << b << endl;
}
private:
string m_name = "test";
};
int main(int argc, char *argv[])
{
// f1的类型为 function<void(int, int)>
// 绑定函数 func1 的第一,二参数值为: 1 2
auto f1 = std::bind(func1, 1, 2);
f1();
// 绑定函数 fun 的第二个参数为 2,而func1 的第一个参数由调用f2的时候指定
auto f2 = std::bind(func1, std::placeholders::_1, 2);
f2(1);
int m = 2;
int n = 3;
auto f3 = std::bind(func2, std::placeholders::_1, n); //表示绑定fun_2的第一个参数为n, fun_2的第二个参数由调用f4的第一个参数(_1)指定。
f3(m);
std::cout << "m = " << m << std::endl; // m=3 说明:bind对于不事先绑定的参数,通过std::placeholders传递的参数是通过引用传递的,如m
std::cout << "n = " << n << std::endl; // n=3 说明:bind对于预先绑定的函数参数是通过值传递的,如n
A a;
// f4的类型为 function<void(int, int)>
auto f4 = std::bind(&A::func3, &a, std::placeholders::_1, std::placeholders::_2); //可以看到这里第二个参数是对象实例
f4(1, 2); //函数中可以直接输出成员变量
return 0;
}
总结
-
对于
std::bind
函数中的参数列表,可以通过std::placeholders
来占用位置,在实际调用的地方再进行指定。 -
预先绑定的参数是通过值传递的,而
std::placeholders
占位符所在位置,跟函数具体参数传递类型有关 -
在实际工作中,经常会用到
bind
绑定类成员函数,这时候第一个参数表示对象的成员函数的指针,第二个参数表示对象的地址,这是因为对象的成员函数需要有this指针。并且编译器不会将对象的成员函数隐式转换成函数指针,需要通过&手动转换;