function和bind
# function
function 是一种函数包装器,也叫做适配器。它可以对可调用对象进行包装,本质就是一个类模板。
#include <iostream>
#include <functional>
using namespace std;
int add(int a, int b) {
return a + b;
}
class Functor {
public:
int operator()(int a, int b) {
return a + b;
}
};
class Add {
public:
static int intAdd(int a, int b) {
return a + b;
}
double doubleAdd(double a, double b) {
return a + b;
}
};
int main() {
//1、包装函数指针(函数名)
function<int(int, int)> func1 = add;
cout << func1(1, 2) << endl;
//2、包装仿函数(函数对象)
function<int(int, int)> func2 = Functor();
cout << func2(1, 2) << endl;
//3、包装lambda表达式
function<int(int, int)> func3 = [](int a, int b) { return a + b; };
cout << func3(1, 2) << endl;
//4、类的静态成员函数
//function<int(int, int)> func4 = Plus::plusi;
function<int(int, int)> func4 = &Add::intAdd; //&可省略
cout << func4(1, 2) << endl;
//5、类的非静态成员函数
function<double(Add, double, double)> func5 = &Add::doubleAdd; //&不可省略
cout << func5(Add(), 1.1, 2.2) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# bind
作用:接受一个可调用对象(callable object),生成一个新的可调用对象来“适应”原对象的参数列表。调用 bind 的一般形式为:auto newCallable = bind(callable, arg_list);
解释说明:
- callable:需要包装的可调用对象。
- newCallable:生成的新的可调用对象。
- arg_list:逗号分隔的参数列表,对应给定的 callable 的参数。当调用 newCallable 时,newCallable 会调用 callable,并传给它 arg_list 中的参数。
- 绑定普通函数:
#include <functional>
int sum(int x, int y) {
return x + y;
}
auto newCallable = bind(sum, placeholders::_1, 200); // _1表示占位符
int ret = newCallable(10, 23); // 210
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 绑定成员函数
class Stu {
public:
Stu(const string &name, int age) : name(name), age(age) {}
Stu() {}
void showInfo(string address, string major) {
cout << "I am " << name << ". my age is " << age
<< ", i from " << address
<< " and majoring in " << major << "." << endl;
}
virtual ~Stu() {}
private:
string name;
int age;
};
Stu stu("zhangSan", 22);
auto newCallable = bind(&Stu::showInfo, &stu, "shanxi", placeholders::_1);
newCallable("software engineer");
// I am zhangSan. my age is 22, i from shanxi and majoring in software engineer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
上次更新: 2025/11/11, 22:03:54