哪些算法要求函子是纯函数?

发布于 2024-11-27 17:50:02 字数 114 浏览 5 评论 0原文

一般来说,该标准要求函子是纯函数,因为允许算法将其函子复制到其核心内容。然而,有一些算法(例如find_if)没有合理的实现来进行任何形式的函子复制。

我们可以依靠这个吗?

Generally the standard requires functors to be pure functions because algorithms are allowed to copy their functors to their heart's content. However, there are some algorithms (e.g. find_if) for which no sane implementation would be doing any form of functor copying.

Can we rely on this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

指尖凝香 2024-12-04 17:50:02

我认为您想问的是哪些函子由于在任意时间被复制而需要无状态。

我想不出任何需要使用自由函数的算法,但大多数/全部肯定需要对象本身不保存状态。您可以做的是让对象拥有对算法调用外部保存的状态对象的引用。然后,函子的任何副本都可以适当地修改该状态对象。

I think what you're trying to ask is which functors need to be stateless due to being copied at arbitrary times.

I can't think of any algorithms that require free functions to be used, but most/all certainly require the object itself to not hold state. What you can do is have the object have a reference to a state object that's held outside the algorithm call. Any copy of the functor can then modify that state object appropriately.

吃颗糖壮壮胆 2024-12-04 17:50:02

“纯函数”是什么意思?

如果你的意思是“函数指针”,那么不是;每个标准算法都可以采用函数对象和函数指针。是的,它们必须是可复制的,但是可复制的函子仍然是函子。

如果你的意思是“可复制”,那么是的。标准库要求赋予算法的类型是可复制的。如果您的仿函数不可复制,您可以使用 boost::reference_wrapper 将不可复制的对象包装在充当引用的可复制容器中。请注意,此模板已作为 std::reference_wrapper 添加到 C++0x。

What do you mean by "pure function?"

If you mean "function pointer", then no; every standard algorithm can take function objects as well as function pointers. Yes, they must be copyable, but a functor that is copyable is still a functor.

If you mean "copyable", then yes. The standard library requires that the type given to algorithms be copyable. If your functor isn't copyable, you can use a boost::reference_wrapper<T> to wrap your non-copyable object in a copyable container that acts as a reference. Note that this template was added to C++0x as std::reference_wrapper<T>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文