#include<iostream>
#include<functional>
using namespace std;
void output(int x,int y)
{
cout << x << " " << y << endl;
}
int main()
{
bind(output, 1, 2);//返回值被忽略,不会打印
bind(output, 1, 2)();//匿名'函数'对象,下同。输出:1 2
function<void(int,int)> f = bind(output, 1, 2);
f(4,5);//1 2
//使用了占位符需要指定实参
bind(output, placeholders::_1, 2)(10);//10 2
std::bind(output, 2, std::placeholders::_1)(10);//2 10
//参数1需要找实参列表第二个实参,但是实参列表只有一个实参
// bind(output, placeholders::_2, 2)(10); ERROR
bind(output, placeholders::_2, 2)(10,20);//20 2
}
绑定普通函数
#include<functional>
#include<iostream>
using namespace std;
void testFunc(int x, int y, const function<void(int, int)>&f)
{
if (x % 2 == 0)
f(x, y);
}
void output_add(int x, int y)
{
cout << "x: " << x
<< " y: " << y
<< " x + y: " << x + y << endl;
}
int main(int argc, char** argv)
{
for (int i = 0; i < 10; i++)
{
auto f = bind(output_add, i + 100, i + 200);//参数有效
testFunc(i, i, f);//参数无效
auto f1 = bind(output_add, placeholders::_1, placeholders::_2);//参数无效
testFunc(i, i, f1);//参数有效
}
}
绑定类成员函数和类成员变量
#include<functional>
#include<iostream>
using namespace std;
class Test
{
public:
void output(int x, int y)
{
cout << x << " " << y << endl;
}
int number = 100;
};
int main(int argc, char** argv)
{
//类成员函数绑定
Test t;
auto f = bind(&Test::output, &t, 520, placeholders::_1);
f(250);//二元函数通过绑定降为一元函数,输出520 250
function<void(int,int)>f1 = bind(&Test::output, &t, 520, placeholders::_1);
f1( 0,100);//520 200
//类成员变量绑定(只能绑定非静态公有成员变量)
auto f2 = bind(&Test::number, &t);
cout << f2() << " " << t.number << endl;//100 100
f2() = 200;
cout << f2() << " " << t.number << endl;//200 200
// f2 != f3 ,f2是仿函数,f3是包装器类型,同理 f != f1
function<int& (void)> f3 = bind(&Test::number, &t);
}