C++ function模板和bind函数

一 std::function 简介

类模板std :: function是一个通用的多态函数包装器。 std :: function的实例可以存储,复制和调用任何可调用的目标 :包括函数,lambda表达式,绑定表达式或其他函数对象,以及指向成员函数和指向数据成员的指针。当std::function对象未包裹任何实际的可调用元素,调用该std::function对象将抛出std::bad_function_call异常。

二 bind简介

函数绑定bind函数用于把某种形式的参数列表与已知的函数进行绑定,形成新的函数。这种更改已有函数调用模式的做法,就叫函数绑定。需要指出:bind就是函数适配器。适配器是一种机制,把已有的东西改一改、做做限制,从而让它适应新的逻辑。
它接受一个可调用对象,生成一个新的可调用对象来适应原对象的参数列表。
bind使用的一般形式:

auto newFun = bind(oldFun,arg_list);

三 例子

#include <functional>
#include <iostream>

int show(string name, int age)
{
    
    
	cout << "name:" << name << "\tage:"<<age << endl;

	return 0;
}

int main()
{
    
    
	// std::function
	using namespace std::placeholders;
	std::function<int(string, int)> func = show;
	func("张A", 100);

	//Lamda
	std::function<int(string, int)> funb = [](string name, int age)->int{
    
    
		cout << "name:" << name << "\tage:" << age << endl;
		return 0;
	};
	funb("张B", 95);

	//bind
	//在bind函数后有一个符号_1,这是一个占位符,代表绑定函数中的第一个参数,_2同理
	auto retfunc = bind(show, _2, _1);//相当于int show(int age, string name)
	retfunc(90,"张C");

	auto retfund = bind(show, _1, _2);//原函数
	retfund("张D", 85);

	auto retfune = bind(show, _1, 80);//相当于int show(int age)
	retfune("张E");

	auto retfunf = bind(show, "张F",75);//相当于int show()
	retfunf();

	system("pause");
	return 0;
}

结果
在这里插入图片描述

四 function使用场景

#include <iostream>
#include <functional>

using namespace std;

std::function<bool(int, int)> fun;
//普通函数
bool compare_com(int a, int b)
{
    
    
	return a > b;
}
//lambda表达式
auto compare_lambda = [](int a, int b) {
    
     return a > b; };
//仿函数
class compare_class
{
    
    
public:
	bool operator()(int a, int b)
	{
    
    
		return a > b;
	}
};
//类成员函数
class compare
{
    
    
public:
	bool compare_member(int a, int b)
	{
    
    
		return a > b;
	}
	static bool compare_static_member(int a, int b)
	{
    
    
		return a > b;
	}
};
int main()
{
    
    
	bool result;
	fun = compare_com;
	result = fun(10, 1);
	cout << "普通函数输出, result is " << result << endl;

	fun = compare_lambda;
	result = fun(10, 1);
	cout << "lambda表达式输出, result is " << result << endl;

	fun = compare_class();
	result = fun(10, 1);
	cout << "仿函数输出, result is " << result << endl;

	fun = compare::compare_static_member;
	result = fun(10, 1);
	cout << "类静态成员函数输出, result is " << result << endl;

	//类普通成员函数比较特殊,需要使用bind函数,并且需要实例化对象,成员函数要加取地址符
	compare temp;
	fun = std::bind(&compare::compare_member,&temp, std::placeholders::_1, std::placeholders::_2);
	result = fun(10, 1);
	cout << "类普通成员函数输出, result is " << result << endl;

	return 0;
}

代码摘自 function

猜你喜欢

转载自blog.csdn.net/GreedySnaker/article/details/114323759