C++ - bind

作用

  • 对可调用实体(函数指针,仿函数,lambda表达式)的一种封装,这种封装能起到预绑定参数的作用。

使用示例:

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
51
52
53
54
55
56
57
58
#include<iostream>
#include<functional>

void global_func(int a) {//全局函数
std::cout << "call global_func:" << a << std::endl;
}

auto labmda = [](int a) {std::cout << "lambda:" << a << std::endl; };

class ClassA {
public:
void member_func(int a) {//类成员函数
std::cout << "call ClassA::member_func:" << a << std::endl;
}

static void static_member_func(int a) {//类静态函数
std::cout << "call ClassA::static_member_func:" << a << std::endl;
}
};

class Functor {//仿函数
public:
void operator()(int a) {
std::cout << "call Functor()" << a << std::endl;
}
};


int main(int argc, const char* argv[]) {
std::function<void(int)> func;
func = global_func;
func(10);
auto bindGlobalFunc = std::bind(global_func, 10);
bindGlobalFunc();

func = labmda;
func(11);
auto bindLabmdaFunc = std::bind(labmda, 11);
bindLabmdaFunc();

Functor testFunctor;
func = testFunctor;
func(12);
auto bindFunctorFunc = std::bind(testFunctor, 12);
bindFunctorFunc();

ClassA a_object;
func = std::bind(&ClassA::member_func, &a_object, std::placeholders::_1);
func(13);
auto bindClassMemberFunc = std::bind(&ClassA::member_func, &a_object, 13);
bindClassMemberFunc();

func = std::bind(&ClassA::static_member_func, std::placeholders::_1);
func(14);
auto bindClassStaticFunc = std::bind(&ClassA::static_member_func, 14);
bindClassStaticFunc();
return 0;
}
  • 输出结果:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    call global_func:10
    call global_func:10
    lambda:11
    lambda:11
    call Functor()12
    call Functor()12
    call ClassA::member_func:13,
    call ClassA::member_func:13
    call ClassA::static_member_func:14
    call ClassA::static_member_func:14

注意事项:

  • 预绑定的参数是以**值传递**的形式
  • 不预绑定的参数要用std::placeholders(占位符)的形式占位,从_1开始,依次递增,是以引用传递的形式
  • std::bind的返回值是可调用实体,可以直接赋给std::function
  • 对于绑定的指针,引用类型参数,调用者需保证在调用之前生命周期还存在
  • std::placeholders表示新的可调用对象的第几个参数和原函数的第几个参数进行匹配