gpt4 book ai didi

c++ - 什么时候无状态类仿函数可以代替 c 风格的函数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:07 25 4
gpt4 key购买 nike

我在 SO 上找到了一些很好的仿函数示例,例如 this第一,所有令人信服的例子似乎都在定义 operator() 的类中使用了状态。

我在一本书中看到了一个例子,它定义了没有状态的函数调用运算符,我不禁觉得这是一种尴尬的用法,而且普通风格的函数指针会比使用 operator() 在这里的每一个方面 - 更少的代码,更少的变量(你必须实例化比较器),由于实例化它可能更有效,并且没有丢失意义或封装(因为它只是一个函数).

我知道 std::sort 允许您在 operator() 类和函数之间进行选择,但由于上述逻辑,我一直只使用函数。

某个类(class)可能受到青睐的原因是什么?

这是示例(释义):

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);

最佳答案

典型的原因是,当您这样做时:

bool less_than(const Point&, const Point&);
// ...
std::sort(..., &less_than);

谓词的模板参数如下:

bool(const Point&,const Point&)

由于排序函数接收函数指针,编译器更难将谓词使用内联到 std::sort() 中。发生这种情况是因为你可以有另一个功能

bool greater_than(const Point&, const Point&);

具有完全相同的类型,这意味着 std::sort() 实例化将在两个谓词之间共享。 (请记住,我说过这会使内联变得更加困难,但并非不可能)。

相反,当您这样做时:

struct less_than {
bool operator()(const Point&, const Point&) const;
};
// ...
std::sort(..., less_than());


struct greater_than {
bool operator()(const Point&, const Point&) const;
};
// ...
std::sort(..., greater_than());

编译器为每个谓词的 std::sort() 生成一个唯一的模板实例化,从而更容易内联谓词的定义。

关于c++ - 什么时候无状态类仿函数可以代替 c 风格的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9288694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com