std::bind函数

std::bind

关于bind的用法:可将bind函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。

auto newCallable = bind(callable,arg_list)
其中,newCallable本身是一个可调用对象,arg_list是一个逗号分隔的参数列表,对应给定的callable的参数。
即,当我们调用newCallable时,newCallable会调用callable,并传给它arg_list中的参数。
在我看来std::bind,其实就是提前绑定某个函数的部分参数或者所有参数后生成一个新的函数。
 1 int showAB(int a,int b)
 2 {
 3     std::cout<<"a="<<a<<" b="<<b<<std::endl;
 4     return a;
 5 }
 6 class Test{
 7 public:
 8     int fun(int a,int b,int c)
 9     {
10         std::cout<<"a:"<<a<<":b:"<<b<<":c:"<<c<<std::endl;
11         return a+b+c;
12     }
13 };
14 int main()
15 {
16     auto f1 = std::bind(showAB,12,22);
17     //相当于生成函数 int(){return showAB(12,22);}
18     f1(2);//输啥都一样
19     auto f2 = std::bind(showAB,std::placeholders::_1,12);
20     //相当于生成函数 int(int a){return showAB(a,12);}
21     f2(1);//影响a
22     Test t;
23     auto f3 = std::bind(&Test::fun,t,1,2,4);
24     //相当于生成函数 int(){t.fun(1,2,4)}
25     std::cout<<f3();
26     return 0;
27 }

转载https://www.jianshu.com/p/07eae70771fb

posted @ 2022-06-06 02:01  Encephalitis  阅读(281)  评论(0)    收藏  举报