【发布时间】:2023-03-10 17:25:01
【问题描述】:
我在 SO 上找到了一些很好的仿函数示例,例如 this one,所有令人信服的示例似乎都在定义 operator() 的类中使用了状态。
我在一本书中遇到了一个例子,它定义了没有状态的函数调用运算符,我不禁觉得这是一个尴尬的用法,而且普通样式的函数指针会比使用 @ 更好987654323@ 在这里的各个方面 - 更少的代码,更少的变量(你必须实例化比较器),由于实例化,它可能更有效,并且没有失去意义或封装(因为它只是一个函数)。
我知道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);
【问题讨论】:
标签: c++ operator-overloading functor