0


c++ bind 函数讲解

1.bind 函数的使用详解

可以将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为第二个参数,以此类推。

绑定成员函数

#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

return 0;

}

对应输出:

#include<iostream>

#include<functional>

using namespace std;

class Plus

{

public:

int plus(int a,int b)

{

    cout<< __func__ << " " << a << " " << b << endl; 

    return a+b;

}

   static int plusEx(int a, int b)  //静态成员函数

   {

        cout<< __func__ << " " << a << " " << b << endl; 

        return  a + b;

   }

};

//bind 可以将既有函数的参数绑定起来,从生成一个函数对象

void function1 (int d)

{

cout << __func__ << " " << d << endl;

}

//如果有多个参数可以只绑定部分

void function2(int d1, int d2)

{

cout<< __func__ << " " << d1 << " " << d2 << endl; 

}

void fun(int& d1, int& d2, int& d3)

{

d1 = 1;

d2 = 2;

d3 = 3;

cout << __func__ << " " << d1 << " " << d2 << " "<< d3 <<endl; 

}

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

//静态成员函数

function<int (int, int)> func3 = std::bind(&Plus::plusEx, placeholders::_1, placeholders::_2);

cout<<func3(4,5)<<endl; //9

auto f = bind(function1,6); //绑定函数function1 的参数

f();

auto ff = bind(function2, placeholders::_1,9); //绑定函数function1 的参数

ff(10);

int m1 = 4, m2 = 5, m3 = 6;

auto fs = bind (fun, placeholders::_1, m2, ref(m3));

fs(m1);

//1.m1是通过placeholders绑定,是传引用绑定,因此在fun内的赋值会影响到m1

//2.m2是通过参数绑定,是传值绑定,在fun内的赋值不会影响到m2

//3.m3是通过ref的传引用绑定,因此在fun内的赋值会影响到m3

cout << func << " " << m1 << " " << m2 << " " << m3 << endl;

return 0;

}

标签: c++ java 前端

本文转载自: https://blog.csdn.net/zuiyijiangnan/article/details/129026414
版权归原作者 月亮+六便士 所有, 如有侵权,请联系我们删除。

“c++ bind 函数讲解”的评论:

还没有评论