摘自:https://www.jianshu.com/p/621fc81a1dc1
作用:
对可调用实体(函数指针,仿函数,lambda表达式)的一种封装,这种封装能起到预绑定参数的作用。
使用示例:
#include <iostream>
using namespace std;
void global_func(int a){//全局函数
cout<<"call global_func:"<<a<<endl;
}
auto labmda = [](int a){cout<<"lambda:"<<a<<endl;};
class ClassA{
public:
void member_func(int a){//类成员函数
cout<<"call ClassA::member_func:"<<a<<endl;
}
static void static_member_func(int a){//类静态函数
cout<<"call ClassA::static_member_func:"<<a<<endl;
}
};
class Functor{//仿函数
public:
void operator()(int a){
cout<<"call Functor()"<<a<<endl;
}
};
int main(int argc, const char * argv[]) {
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;
}
输出结果:
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表示新的可调用对象的第几个参数和原函数的第几个参数进行匹配