Which algorithms require functors to be pure functions?
Generall开发者_运维技巧y 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?
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.
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>
.
精彩评论