我在 SO 上找到了一些很好的函子示例,例如this一,所有令人信服的例子似乎都在定义的类中使用了状态operator()
.
我在一本书中遇到一个例子,它定义了没有状态的函数调用运算符,我不禁觉得这是一种尴尬的用法,并且普通风格的函数指针会比使用更好operator()
这里的各个方面 - 更少的代码,更少的变量(您必须实例化比较器),由于实例化,它可能更有效,并且不会丢失意义或封装(因为它只是一个函数)。
I know std::sort
让你可以选择operator()
类和函数,但由于上述逻辑,我总是只使用函数。
某个班级可能受到青睐的原因是什么?
这是示例(已转述):
class Point2D {
//.. accessors, constructors
int x,y;
};
class HorizComp {
public:
bool operator()(const Point2D& p, const Point2D& q) const
{ return p.getX() < q.getX(); }
};
class VertComp {
public:
bool operator()(const Point2D& p, const Point2D& q) const
{ return p.getY() < q.getY(); }
};
template <typename E, typename C>
void printSmaller(const E& p, const E& q, const C& isLess) {
cout << (isLess(p, q) ? p : q) << endl; // print the smaller of p and q
}
//...
// usage in some function:
Point2D p(1.2, 3.2), q(1.5, 9.2);
HorizComp horizComp;
VertComp vorizComp;
printSmaller(p, q, horizComp);
printSmaller(p, q, vorizComp);