C++零碎知识(1)--function(STL)

C++零碎知识–function(STL)

1.简介
std::function属于STL,是一个通用的多态函数包装器,可用于保存调用函数、bind表达式、lambda函数、成员函数或对象的指针。

function类模板的语法格式为:

#include<functional>
using namespace std;
template<class R,class... Args>//R,被调用的返回类型。
class function<R(Args...)>;//Args,被调函数的形参。

2.使用实例

·普通函数

void normfun(){
	cout << "Ok" << endl;
}

int main(){
	function<void()> f1 = normfun;
	f();
 
	system("pause");
	return 0;
}

·模板函数

template <typename T>
T num_add(T x, T y){
	return x + y;
}
 
int main(){
	function<int(int,int)> f2 = num_add<int>;
	f(1,2);
 
	system("pause");
	return 0;
}

·函数对象

template<typename T>
struct num_add{				
public:
    T operator() (T x, T y){
        return x + y;
    }
};
int main(){
   num_add fc;
   function<int(int,int)> func = fc<int>();
   cout<<func(1,2)<<endl; 
   system("pause");
   return 0;
}

·类成员函数

class A{
public:
    //类静态函数
	static int Add1(int x, int y){
		return x + y;
	}
	//类静态模板函数
	template<typename T>
	static T Add2(T x, T y){
		return x + y;
	}
    //普通类函数
	int Add3(int x, int y){
		return x + y;
	}
};
 
int main(){
	//1、 类静态函数
	function<int(int, int)> f1 = &A::Add1;
	cout << f1(1, 2) << endl;
 
	//2、 类静态模板函数
	function<int(int, int)> f2 = &A::Add2<int>;
	cout << f2(1, 2) << endl;
 
	//普通类函数绑定  需要构造类对象
	A a;
 
	//3、 普通函数 需使用bind,将类对象地址 &c 绑定上
	function<int(int, int)> f3 = std::bind(&A::Add3, &a, placeholders::_1, placeholders::_2);    
	cout << f3(1, 2) << endl;
 
	//4、普通函数, 也可以这样调用  个人觉得这个比 bind 麻烦,不建议
	function <int(const A&, int, int)> f4 = &A::Add3;
	cout << f4(c,1, 2) << endl;
	
	system("pause");
	return 0;
}

·Lambda表达式

int main(){
	auto func = [](const int x, const int y) {return x + y; };
	function<int(int, int)>func = f;
	cout << func(1, 2) << endl;  
	   
	system("pause");
	return 0;
}

3.为何要使用function模板?STL只会对对具有实际使用价值的操作进行封装,function可以统一处理不同类型函数对象,不必使用繁琐的指针(指针也挺好,但有时候户比较麻烦),加快了开发效率。

4.待补充

参考资源:
点击访问:https://en.cppreference.com/w/cpp/utility/functional/function
点击访问:https://blog.csdn.net/qq_35721743/article/details/83217416

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值