Reputation: 43
I realize it amounts to syntactic sugar but, with the advent of lambda, I would have loved to be able to type
std::for_each(list, [](Emitter& e) { e->emit() });
instead of
std::for_each(list.begin(), list.end(), ....);
I get the later is more generally usable but they could have provided both (AFAICT the former would simply be another template function)
Upvotes: 1
Views: 160
Reputation: 7637
With the advent of lambdas, here come range-based for
loops as well:
for (auto &e: list)
e.emit();
Upvotes: 2
Reputation: 3530
Guess what? You can! ;-) By defining your own for_each
function:
template <class C, class F>
F for_each(C const& c, F f) {
return std::for_each(std::begin(c), std::end(c), f);
}
You can see a live example here: http://ideone.com/gwGNGL
Upvotes: 3
Reputation: 101456
Since I'm not on the Comittie, what follows is speculation. But seems legit to me.
Is there a reason std::for_each was not written to take a std::list?
Code bloat.
Providing both for_each (begin, end)
and for_each (container)
would have been effectively redundant. After all, as you said, you could simply write for_each (c.begin(), c.end())
and get exactly the behavior you want.
Since the version you propose is just syntactic sugar for, and more restrictive than the version that is part of the library (which takes begin
and end
iterators), there was no point in adding it.
I suppose you could think of this as an extension of the "don't pay for what you don't want" philosophy that guides much of C++'s overall design. As mentioned eslewhere, you could very simply provide your own fairly generic function. Here's some psudocde illustrating such:
namespace blah
{
template <typename Cont, typename UnaryFunction> inline UnaryFunction for_each (Cont& cont, UnaryFunction f)
{
return std::for_each (cont.begin(), cont.end(), f);
}
}
Upvotes: 1
Reputation: 119847
Standard algorithms work with ranges, not with containers. That's a deliberate design decision. The standard library should not be bloated. If you want to add this functionality yourself, you trivially can.
Upvotes: 1