Which algorithms require functors to be pure funct

2019-07-21 10:12发布

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?

标签: c++ functor
2条回答
可以哭但决不认输i
2楼-- · 2019-07-21 10:38

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.

查看更多
放我归山
3楼-- · 2019-07-21 10:42

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

查看更多
登录 后发表回答