
大家好,又见面了,我是你们的朋友全栈君。
可以将bind函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。
调用bind的一般形式:auto newCallable = bind(callable,arg_list);`
其中,newCallable本身是一个可调用对象,arg_list是一个逗号分隔的参数列表,对应给定的callable的参数。即,当我们调用newCallable时,newCallable会调用callable,并传给它arg_list中的参数。
arg_list中的参数可能包含形如_n的名字,其中n是一个整数,这些参数是“占位符”,表示newCallable的参数,它们占据了传递给newCallable的参数的“位置”。数值n表示生成的可调用对象中参数的位置:_1为newCallable的第一个参数,_2为第二个参数,以此类推。
1. 绑定普通函数
#include<iostream>
#include<functional>
using namespace std;
int plus(int a,int b)
{
return a+b;
}
int main()
{
//表示绑定函数plus 参数分别由调用 func1 的第一,二个参数指定
function<int(int,int)> func1 = std::bind(plus, placeholders::_1, placeholders::_2);
//func2的类型为 function<void(int, int, int)> 与func1类型一样
auto func2 = std::bind(plus,1,2); //表示绑定函数 plus 的第一,二为: 1, 2
cout<<func1(1,2)<<endl; //3
cout<<func2()<<endl; //3
retunrn 0;
}2. 绑定类的成员函数
#include<iostream>
#include<functional>
using namespace std;
class Plus
{
public:
int plus(int a,int b)
{
return a+b;
}
}
int main()
{
Plus p;
// 指针形式调用成员函数
function<int(int,int)> func1 = std::bind(&Plus::plus,&p, placeholders::_1, placeholders::_2);
// 对象形式调用成员函数
function<int<int,int>> func2 = std::bind(&Plus::plus,p, placeholders::_1, placeholders::_2);
cout<<func1(1,2)<<endl; //3
cout<<func2(1,2)<<endl; //3
retunrn 0;
}占位符_1位于placeholders的命名空间,而placeholders位于std的命名空间中
3. 绑定类静态成员函数
#include<iostream>
#include<functional>
using namespace std;
class Plus
{
public:
static int plus(int a,int b)
{
return a+b;
}
}
int main()
{
function<int(int,int)> func1 = std::bind(&Plus::plus, placeholders::_1, placeholders::_2);
cout<<func1(1,2)<<endl; //3
retunrn 0;
}参考:primer C++ 第五版
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/219175.html原文链接:https://javaforall.cn