The legacy std::for_each
returns function as the standard only requires Function
to meet Cpp17MoveConstructible according to [alg.foreach]:
template<class InputIterator, class Function> constexpr Function for_each(InputIterator first, InputIterator last, Function f);
Preconditions:
Function
meets the Cpp17MoveConstructible requirements.[Note:
Function
need not meet the requirements of Cpp17CopyConstructible. end note]
This is reasonable since the user may want to reuse the function after the call.
The parallel version of for_each
has no return:
template<class ExecutionPolicy, class ForwardIterator, class Function> void for_each(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Function f);
Preconditions:
Function
meets the Cpp17CopyConstructible requirements.
This is because the standard requires Function
to meet the Cpp17CopyConstructible, so returning the function is unnecessary as the user can freely create a copy if they want on the call side.
I noticed that ranges::for_each
also returns the function:
template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirectly_unary_invocable<projected<I, Proj>> Fun> constexpr ranges::for_each_result<I, Fun> ranges::for_each(I first, S last, Fun f, Proj proj = {});
However, the function signature already requires Fun
to satisfy indirectly_unary_invocable
which already guarantees that it is copy constructible.
The question is, why does the ranges::for_each
still return the function? What's the point of doing this?
std::for_each
. But that's pure speculation. – Pyorrhea