for_each
as a non-modifying sequence operation, and the function object passed to for_each
should not modify its argument. The requirements for the arguments of for_each
are unnecessary strict, since as long as the iterators are mutable, for_each
accepts a function object that can have side-effects on their argument. Nevertheless, it is straightforward to provide another function template with the functionality of std::for_each
but more fine-grained requirements for its arguments.
Thus, using lambda library facilities with for_each
becomes virtually illegal given the fact that much of the usefulness comes with the possibility to actually change the elements of the sequence provided to for_each
. I also think that the comment by Järvi and Powell about what for_each
accepts could be misleading, because some STL implementation could decide to enforce the fact that for_each
is a non-mutating algorithm thus preventing us from using it as a mutating one (and changing STL platform doesn't seem a good idea in this case, but this is a personal opinion).
Thus, it could be useful to have another algorithm, which we could call on_each
, implemented in the most straighforward way:
//Performs f() on any element elem in [first, pastlast) template<typename InputIterator, typename UnaryFunction> UnaryFunction on_each(InputIterator first, InputIterator pastlast, UnaryFunction f) { for (; first != pastlast; ++first) f(*first); return f; }
in order to:
for_each
while providing the same functionality;
Maybe, the definition of for_each
should be revised as well with more fine-grained requirements for its arguments, but I'm wondering how much code relies on its side effects now and how tough would be adjust all the uses :)