C++-标准库bind函数

简介

bind函数看做一个通用的函数适配器,它接受一个可调用对象callable,生成一个新的可调用对象newCallable。

1
auto newCallable = bind(callable, arg_list);

用法

1. 绑定普通函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
int plusF(int a, int b)
{
return a + b;
}
int main()
{
//表示绑定函数plus 参数分别由调用 func1 的第一,二个参数指定
auto func1 = bind(plusF, std::placeholders::_1, std::placeholders::_2);
auto func2 = bind(plusF, 1, 2);
cout << func1(1, 2) << endl; //3
cout << func2() << endl; //3
return 0;
}

2. 绑定类的成员函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
class PlusC
{
public:
int plus(int a, int b)
{
return a + b;
}
};
int main()
{
PlusC p;
// 指针形式调用成员函数
auto func1 = std::bind(&PlusC::plus, std::placeholders::_1, std::placeholders::_2);
// 对象形式调用成员函数
auto func2 = std::bind(&PlusC::plus, p, std::placeholders::_1, std::placeholders::_2);
cout << func1(1, 2) << endl; //3
cout << func2(1, 2) << endl; //3
return 0;
}

3. 绑定类静态成员函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <memory>
#include <functional>
using namespace std::placeholders;
using namespace std;
class Plus
{
public:
static int plus(int a,int b)
{
return a+b;
}
}
int main()
{
auto func1 = std::bind(&Plus::plus, _1, _2);
cout<<func1(1,2)<<endl; //3
retunrn 0;
}