Why does std::for_each(from, to, function) return function?

Viewed 9097

I just read the code for std::for_each:

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
  for ( ; first!=last; ++first ) f(*first);
  return f;
}

and could not see any good reasons for this template function to return the input function. Does anyone have any examples on where this would be useful?

6 Answers

If you pass in a function object, aka functor, and it has state, returning the function object allows you to access its state after iterating the sequence. Let's say you had a function object that computes three different variables from the sequence and holds them in member variables. Each time the functor is called, you update the counters. If for_each didn't return the object, how would you get the result?

Note... this is why you must always implement copy-construction, and assignment for function objects with state.

Returning the function basically makes std::for_each into a mediocre imitation of std::accumulate. It lets you accumulate something in the function/functor, and then retrieve that accumulated value when it's done. Almost any time you think this might be a useful thing to do, you should probably consider using std::accumulate instead.

its useful if you want to save (and later use) the functor state between calls for example, count the number of elements in a collections or indicate some failure to process an element by setting some internal variable.

No particular reason I guess. What you can do though is using the returned function in another foreach call, thus avoiding writing the function name twice and possibly making a mistake there.

Related