c++ function和bind

为什么要用std::function 因为 函数指针,函数对象,匿名函数都可以作为调用对象 即高阶函数调用对象
然而并不是所有函数都可以被高阶函数调用因此要用function 列如类
function 可以创建对象 他可以接受任意类型可以调用对象 而且还可以用数组存储一个函数容器 但是函数参数格式必须一样
std::bind 是一个函数适配器 他接收一个函数和一组实参 返回一个function函数对象
using namespace std::placeholders; // bind如果不想过早传递参数可以用 placeholders 有占位符 如 bind(lesst,_1,_2);站了两个参数的位下面在调用
函数指针
函数对象
匿名函数
回调函数

#include <iostream>
#include <functional> // 必须要这个头文件
using namespace std;
using namespace std::placeholders; // bind如果不想过早传递参数可以用 placeholders 有占

int lesst(const int& a, const int& b) { return a < b ? a : b; }

template<typename T>
int greate(const T& a, const T& b) { return a > b ? a : b; }

class Lesst {
public:
	int operator()(const int& a, const int& b) { return a < b ? a : b; }
};

void fun(function<int(const int x, const int y)>com[],int n,int a,int b) {
	for(int i=0;i<n;i++)
		cout<<com[i](a, b)<<endl; //用下标打印存储的每个函数 分别调用 
}
int main() {
	int a{ 3 }, b{ 8 },n=0;
	std::function<int(const int x, const int y)>compare; // function创造了一个可以接受任意int类型函数对象的对象
	compare = lesst; //int(const int x, const int y) 可以接受任意类型
	cout << compare(a, b) << endl; //调用普通函数
	compare = greate<int>;
	cout << greate(a, b) << endl; // 调用模板函数
	compare = Lesst();
	cout << compare(a, b) << endl; //调用对象函数
	int v = 3;
	auto pf = [&v, &compare](int a, int b) { 
	int x{ abs(a - v) }; 
	int y{ abs(b - v) };
	return x < y ? a : b; 
	};
	compare = pf;
	cout << compare(a, b) << endl;// 调用匿名函数
	cout << endl;

	function<int(const int x, const int y)>compare2[]{ lesst,greate<int>,Lesst(),pf };
	fun(compare2,4,a,b); // 丢compare2整个函数数组
	cout << endl;

	auto f = std::bind(Lesst(), 1, 2); // 其中f已经包含了参数 1 2
	std::function<int()>ff = std::bind(Lesst(), 3, 5); // 因为已经丢参了function可以<int()>
	cout << f() <<"\t"<<ff()<< endl;
	auto fbind = std::bind(pf, 5,_1); // 占位一个 位置对应的
	auto ftf = std::bind(pf, _1, _2); // 占位两个 下面调用就要丢两个
	std::function<int(const int x, const int y)>fsf = std::bind(pf, 3, _2); // 用了占位符要明确function类型
	cout << fbind(3) << "\t" << ftf(5, 3) <<"\t"<<fsf(3,6)<< endl; // fbind只是占用一个 ftf占用两个所以调用也是一样的
	std::function<int(const int x, const int y)>flact[]{ fbind,ftf,fsf };
	for (int i = 0; i < v; i++)
		cout << flact[i](3, 5) << endl; //又要重新丢参= =
	while (true);
	return 0;
}

	//int fun(int(*pf)(int), int x) { // 这里用 (function<int(int)>f,int x) 就没错可以接收任意类型的函数
	//	return pf(x);
	//}
	//int add2(int x) { return x + 2; }
	//class AddOne {
	//public:
	//	int operator()(int x) { return x + 1; }
	//};

	//auto a{ 5 };
	//cout << fun(add2, a) << endl;
	//cout << fun([](int x) {return x * x; }, a) << endl;
	//cout << fun(AddOne(), a) << endl; 可以看出函数对象不能被fun调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值