function类型介绍
可调用对象的概念
可调用对象:一个类重载了()运算符,我们就可以像调用函数一样,调用这个类的对象。也有称为“函数对象”,“仿函数”。
#include <iostream>
class A{
public:
A(){
std::cout << "构造函数" << std::endl;
}
~A(){
std::cout << "析构函数" << std::endl;
}
int operator()(int value){
if(value > 0){
std::cout << "value是正数" << std::endl;
}
return value;
}
};
int main() {
A a;
a(100);
return 0;
}
上面的A类重载了()运算符,则A类的对象a就可以像调用函数一样调用a对象,这就叫做可调用对象。
调用形式
调用形式:函数返回值和函数参数组成调用形式。
如上面:
int operator()(int value){
if(value > 0){
std::cout << "value是正数" << std::endl;
}
return value;
}
这个函数的调用形式为:int(int) 前面的int是函数返回值类型,括弧里面的int是参数类型。
function类模板
C++11,标准库定义了function类模板。作用是用来包装可调用对像,和函数。
用法
包含头文件include <functional>
模板类实例化
function<调用形式>
如:function<int(int)> 表示包装一个返回值是int ,参数是int的函数或者可调用对象。
#include <iostream>
#include <functional>
class A{
public:
A(){
std::cout << "构造函数" << std::endl;
}
~A(){
std::cout << "析构函数" << std::endl;
}
int operator()(int value){
if(value > 0){
std::cout << "value是正数" << std::endl;
}
return value;
}
};
int compare(int value){
if(value < 0){
std::cout << "value是负数" << std::endl;
}
}
int main() {
A a;
std::function<int(int)> fn1 = a;
std::function<int(int)> fn2 = compare;
fn1(100);
fn2(-1);
return 0;
}
结果:
构造函数
析构函数
value是正数
value是负数
function使用注意问题
若有重载函数,function将不知道包装哪一个函数。
int compare(){
std::cout << "比较" << std::endl;
return 0;
}
int main() {
A a;
std::function<int(int)> fn1 = a;
//std::function<int(int)> fn2 = compare; //错误,无法包装对应的compare函数
/*解决办法*/
int (*f)(int) = compare;
std::function<int(int)> fn2 = f;
fn1(100);
fn2(-1);
return 0;
}