遗留的`std::for_each`函数返回函数,因为标准只要求`Function`满足Cpp17MoveConstructible,根据[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]
for_each
的并行版本没有返回值。
这是因为标准要求
template<class ExecutionPolicy, class ForwardIterator, class Function> void for_each(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Function f);
Preconditions:
Function
meets the Cpp17CopyConstructible requirements.
Function
满足Cpp17CopyConstructible,所以返回函数是不必要的,因为用户可以在调用端自由地创建副本。我注意到
ranges::for_each
也返回函数:
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 = {});
然而,函数签名已经要求Fun
满足indirectly_unary_invocable
,这已经保证了它是可复制的。问题是,为什么
ranges::for_each
仍然返回函数?这样做有什么意义呢?
std::for_each
的替代品插入进来。但这只是纯粹的猜测。 - undefined