std::function是一个函数包装器模板,它可以存储、复制和调用任何可调用对象。它是一个类型擦除容器,提供了统一的接口来处理各种可调用实体。
一、基本定义
#include <functional>
std::function<返回值类型(参数类型列表)> 函数对象;
可以存储什么?
std::function可以存储几乎所有可调用对象;
普通函数
int add(int a,int b){
return a + b;
}
int sub(int x,int y){
return y - x;
}
void test(void){
function<int()> f = bind(&add,3,4); // 如果希望不绑定如何参数,参数列表为空
cout << "function存储普通函数 f()" << f() << endl;
// 否则,如果想要含参输入
using namespace std::placeholders;
function<int(int,int)> f1 = bind(&sub,_1,_2);
cout << "function存储普通函数 f(int,int)" << f1(1,9) << endl;
}
成员函数(需要特殊处理)
class Math{
public:
int area(int x , int y) const{
return x * y;
}
};
void test0(void){
Math math;
using namespace std::placeholders;
function<int(int,int)> f = bind(&Math::area,&math,_1,_2);
cout << "成员函数f() " << f(3,3) << endl;
}
函数指针
int add(int a,int b){
return a + b;
}
void test2(void){
// 定义函数指针
int (*func_ptr)(int,int) = &add;
function<int(int,int)> f = func_ptr;
cout << "绑定函数指针" << f(5,6) << endl;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。