今天主要是学习了14.8函数调用运算符。函数调用运算符必须是成员函数。下面是一个例子
class PrintString {
public:
PrintString(ostream &o = cout, char c = ' ') :
os(o), sep(c) {}
void operator()(const string &s)const { os << s << sep; }
private:
ostream & os;
char sep;
};
lambda表达式是函数对象。lambda类似于一个模板,在使用它时实现。在使用lamda时非常像使用了相应类的重载运算成员。
之后是标准库定义的函数对象,但书中的很多对象在现行c++14中不在适用,个人认为没有太大必要使用运算符对象,举例:
plus<int> ip;\\定义了一个模板实现
int i=ip(1,2);
之后是可调用对象和function。
类,lambda,函数之间或许有不同的功能,但只要其共有相同的返回值和形参类型就称为有相同的调用形式。int(int,int).
我们可以使用function类表示同一种调用形式的通用类,function在<functional>中。利用map可以将所有有相同调用形式的谓词集合起来。以下为实例:
int add(int i, int j)
{
return (i + j);
}
int main()
{
map<string, int(*)(int, int)> binops;
binops.insert({ "+",add });
function<int(int, int)> f1 = add;
function<int(int, int)> f2 = [](int i, int j) { return i - j; };
map<string, function<int(int, int)>> fmap;
fmap.insert({ "+",add });
fmap.insert({ "-",f2 });
fmap.insert({ "*",[](int i,int j)-> int {return i * j; } });
fmap["/"] = [](int i, int j) {return i / j; };
int c = fmap["*"](10, 3);
cout << c << endl;
cout << fmap["/"](30, 3) << endl;
return 0;
}
可以看到fmap中集合了+,-,*,/四种fucntion。这一点还是非常有实际意义的。