std::bind()

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

头发乌黑茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值