Which algorithms require functors to be pure functions?

随声附和 提交于 2020-01-05 01:33:59

问题


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?


回答1:


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.




回答2:


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>.



来源:https://stackoverflow.com/questions/6919766/which-algorithms-require-functors-to-be-pure-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!