C++新特性 函数对象包装器function与bind

#include <functional>

//函数对象包装器
/*  加上头文件#include <functional>

	1.为函数提供了一种容器(封装)
	2.支持4种函数的封装
	2.1普通函数
	2.2匿名函数
	2.3类的成员函数
	2.4仿函数(重载了()运算符的函数)
*/
using namespace std;

class Test
{
	public:
		int test01(int n)
		{
			return n;
		}
		//仿函数
		int operator()(int n)
		{
			return n;
		}
};

int test(int n)
{
	cout << n << endl;
	return n;
}


int test01(int a,int b,int c)
{
	cout << a <<b<<c<< endl;
	return a+b+c;
}

int main()
{

	//普通函数封装
	test(1);
	//相当提供了一个函数指针包装了(封装函数),把函数当对象处理
	function<int(int)> f = test;

	f(123); // test(123); 结果一样 只想相同的函数地址

	//匿名函数
	function<int(int)> f2 = [](int n)->int
	{
		cout << n << endl;
		return n;
	};
	//类成员函数(由于类构造的时候会有一个隐藏的this指针,所以需要传递一个指针,用于指明一个对象)
	function<int(Test*, int)> f3 = &Test::test01;
	Test t;
	f3(&t,123);
 

	//仿函数
	function<int(Test*, int)> f4 = &Test::operator();
	Test t01;
	f3(&t01, 123);


	//bind机制 将函数绑定起来	
	auto a = bind(test01, 1, 2, 3);
	a();
	auto b = bind(test01, std::placeholders::_2, std::placeholders::_1, 3);//placeholders::_1将这个参数预定
	b(1,2);//这个传入的参数就是std::placeholders::_1所指代的参数,按占位符号传参数



	while (true)
	{

	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值