function函数对象包装器和bind机制

支持四种函数的包装:

  • 普通函数

  • 匿名函数

  • 类的成员函数

  • 仿函数(重载了()运算符的函数)

  • bind

  //函数对象包装器
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
//函数对象包装器,为函数提供了一种容器(封装)

int test(int n)
{
	cout << n << endl;
	return n;
}
class Test
{
public:
	Test() = default;
	int Mytest(int n)
	{
		cout << n << endl;
		return n;
	}
	//仿函数的写法
	int operator()(int n)
	{
		cout << n << endl;
		return n;
	}
};
void mytest(int a, int b, int c)
{
	cout << a << " " << b << " " << c << endl;
}
int main()
{
	//普通函数直接调用
	test(123);
	//<int(int)>  ()里的int是参数列表,另一个int是返回值
	std::function<int(int)> f1 = test;  //模板的写法
	//f 装的就是 test函数体本身
	//调用时直接用函数对象去调用就行了,把函数封装成对象

	//1.普通函数
	f1(123);

	//2.匿名函数
	std::function<int(int)> f2 = [](int n)->int
	{
		cout << n << endl;
		return n;
	};
	f2(123);

	//3.类的成员函数
	std::function<int(Test*, int)> f3 = &Test::Mytest;   //有个this指针
	Test t;
	f3(&t, 123);

	//直接调用重载的()运算符
	t(123);

	//仿函数的调用
	//仿函数(重载了()运算符的函数)
	std::function<int(Test*, int)> f4 = &Test::operator();
	f4(&t, 123);

	//bind机制
	auto f = bind(mytest, 10, 20, 30);
	f(); //10 20 30

	auto ff = bind(mytest, 10, placeholders::_1, 30); //  placeholders::_1 表示第一个占位符,调用时再给出
	ff(40);  //10 40 30

	auto fff = bind(mytest,placeholders::_2, placeholders::_1, 3); //有两个占位符,_1表示第一个,_2表示第二个
	fff(10,5);  //5 10 3  (调用时不是直接参数对应(而是打乱了顺序),10为第一个参数,对传递给 _1,5会传递给 _2)

	auto ffff = bind(mytest, 1, placeholders::_1, 3);
	ffff(30, 20, 40);  //1 30 3  (1和3已经给定了,只会对未给定的占位符起作用,20和30不起作用)
	//ffff(30,20,40,50,60)  //参数多出了50和60,也不会报错

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值