std::bind是这样一种机制,它可以预先把指定可调用实体的某些参数绑定到已有的变量,产生一个新的可调用实体,这种机制在回调函数的使用过程中也颇为有用。
C++98中,有两个函数bind1st和bind2nd,它们分别可以用来绑定functor的第一个和第二个参数,它们都是只可以绑定一个参数,各种限制,使得bind1st和bind2nd的可用性大大降低。
在C++11中,提供了std::bind,它绑定的参数的个数不受限制,绑定的具体哪些参数也不受限制,由用户指定,这个bind才是真正意义上的绑定。
std::bind的基本语法:
#include <iostream>
#include <functional> //std::bind
using namespace std;
void func(int x, int y)
{
cout << x << " " << y << endl;
}
int main()
{
bind(func, 1, 2)(); //输出:1 2
bind(func, std::placeholders::_1, 2)(1);//输出:1 2
using namespace std::placeholders; // adds visibility of _1, _2, _3,...
bind(func, 2, _1)(1); //输出:2 1
bind(func, 2, _2)(1, 2); //输出:2 2
bind(func, _1, _2)(1, 2); //输出:1 2
bind(func,_2, _1)(1, 2); //输出:2 1
//err, 调用时没有第二个参数
//bind(func, 2, _2)(1);
return 0;
}
std::placeholders::_1是一个占位符,代表这个位置将在函数调用时,被传入的第一个参数所替代。
std::bind和std::function配合使用:
#include <iostream>
#include <functional> //std::cout
using namespace std;
using namespace std::placeholders; // adds visibility of _1, _2, _3,...
class Test
{
public:
int i = 0;
void func(int x, int y)
{
cout << x << " " << y << endl;
}
};
int main()
{
Test obj; //创建对象
function<void(int, int)> f1 = bind(&Test::func, &obj, _1, _2);
f1(1, 2); //输出:1 2
function< int &()> f2 = bind(&Test::i, &obj);
f2() = 123;
cout << obj.i << endl;//结果为 123
return 0;
}
通过std::bind和std::function配合使用,所有的可调用对象均有了统一的操作方法。