总述
- ()圆括号是函数调用的明显标记,()也叫函数调用运算符;
- 如果在类中重载了函数调用运算符,就可以想使用函数一样使用该类的对象了;
- 只要对象所属的类重载了()函数运算符,那么这个类对象就变成了可调用的;而且可以调用多个版本的(),只要在参数类型或者数量上有差别即可;
- 重载了()的类实例化的对象,称为函数对象;因为可以调用这些对象;
#include <iostream>
#include <functional>
using namespace std;
//如果值小于0,返回0;否则返回实际值;
class Zero
{
public:
Zero(int x)
{
cout << "Zero(int x)" << endl;
}
int operator()(int value) const
{
if (value < 0) return 0;
return value;
}
int operator()(int value, int x) const
{
if (value < 0) return 0;
return value;
}
};
int main()
{
Zero obj(1);
//定义一个对象,在()中增加实参列表;
int res = obj.operator()(10);
cout << res << endl;
res = obj(2);
cout << res << endl;
return 0;
}
不同调用对象的相同调用形式
标准库function类型介绍
-
function类模板:要提供模板参数来表示该function类型能够表示的对象的调用形式;
function<int(int)> 声明了一个function类型,用来代表一个可调用对象,它所代表的这个可调用对象是:参数为int,返回值为int
#include <iostream>
#include <functional>
#include <map>
using namespace std;
//如果值小于0,返回0;否则返回实际值;
class Zero
{
public:
int operator()(int value) const
{
if (value < 0) return 0;
return value;
}
};
//一种调用形式,对应一个函数类型int(int)
int echo_val(int value) //调用参数和返回值和Zero中的int operator()(int value) const相同,即调用形式相同;
{
cout << value << endl;
return value;
}
//int echo_val()
//{
// return 1;
//}
int main()
{
//可调用对象:
// 1. echo_val 函数;
// 2. Zero中的int operator()(int value) const
Zero obj;
//hashmap.insert({ "zero", obj });
//hashmap.insert({ "zero", Zero });
function<int(int) > f1 = obj; //类对象,因为类有()重载
function<int(int) > f2 = echo_val; //函数指针
function<int(int)> f3 = Zero(); //用类名生成一个对象;
f1(2);
f2(3);
f3(0);
//把这些可调用对象的指针保存起来,目的方便随时调用这些可调用对象,这些指针类似与C语言中的函数指针;
//map key-value
map<string, function<int(int)>> hashmap;
hashmap.insert({ "e_v", echo_val}); //echo_val有重载版本,编译报错;无法放到function<int(int)>中;
hashmap.insert({ "b_t", obj});
hashmap.insert({ "zero", Zero() });
hashmap["e_v"](10);
////echo_val有重载版本,编译报错;无法放到function<int(int)>中;通过定义函数指针来解决;
int (*fp)(int) = echo_val;
function<int(int) >fff = fp; //直接将函数指针赋值给function类对象;
//int (*ff) () = echo_val;
return 0;
}