0
点赞
收藏
分享

微信扫一扫

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

1,函数对象包装器

函数对象包装器的意思是将整个函数包装起来,包装成一个容器,以后要使用该函数的时候只需要调用该容器即可。
头文件#include<functional>
例子:
在这里插入图片描述
函数对象包装器支持4种函数的包装,使得函数的表达都成了一个统一的整体。
1,普通函数
2,匿名函数
3,普通成员函数
4,仿函数(重载了运算符()的函数)
其中1的对象包装已经演示过,而下面的代码演示了全部四种函数的包装。读者可直接通过运行下面代码理解

#include<iostream>
#include<functional>
using namespace std;

void test(int i)
{
	cout << "普通函数中i=" <<i<< endl;
}

class A {
public:
	void myfun(int i) {
		cout << "成员函数myfun中i=" << i << endl;
	}

	int operator()(int i) {//重载了()运算符
		cout << "仿函数中i=" << i << endl;
		return i;
	}
};
int main()
{
	function<void(int)> f = test;  //函数对象包装器f将void test(int i) 包装
	f(10);//通过函数对象包装器调用函数

	function<int(int)> f1 = [](int i)->int {
		cout<< "成员函数myfun中i=" << i << endl;
		return i;
	};
	f1(11);

	function<void(A*, int)>f2 = &A::myfun;//注意,成员函数其实还有参数this指针
	A obj;
	f2(&obj, 12);

	function<int(A*, int)>f3 = &A::operator();
	f3(&obj, 13);
}

2,bind机制

bind机制和前面学过的函数的默认参数有点相似,都是指定了默认参数。而原来的默认参数是只能提前指定后n位的参数为默认参数并设定默认值;bind机制则是可以绑定某些特定的参数为特定值。具体用法看下面的示例:

#include<iostream>
#include<functional>
using namespace std;

void bindtest(int a, int b, int c)
{
	cout << "a="<<a <<' ' << "b=" << b <<' '<< "c="<< c<<endl;
}
int main()
{

	auto g = bind(bindtest, 1, 2, 3);//指定a,b,c参数默认为1,2,3
	auto g1 = bind(bindtest, 1, placeholders::_1, 3);//指定a,c的默认参数为1,3,b的参数运行时确定
	auto g2= bind(bindtest, placeholders::_2, placeholders::_1, 3);//指定c的默认参数为3,a,b的参数运行时确定,
	      //且注意 placeholders::_2, placeholders::_1,分别代表函数调用时候的第二个参数以及第一个参数
	g();
	g1(2);
	g2(1, 2);

}
举报

相关推荐

0 条评论