
On Thu, Jan 31, 2013 at 1:58 PM, Thomas Heller <thom.heller@gmail.com> wrote:
On 01/31/2013 10:31 AM, Tim Blechmann wrote:
hi all,
since c++11 has lambda functions, writing functors is easier than never before ... so, i wonder, what do people think about a small utility function, that calls a functor N times?
ruby: 10.times { puts 'hello world' }
supercollider: 10.do { "hello world".postln }
c++11/boost proposal: boost::loop(10, [] { printf("hello world\n"); }); boost::loop(10, [](int index) { printf("hello %d\n, index); });
personally, i find this coding style more elegant than for loops, as it avoids the visual noise of explicitly counting a loop variable ... not sure, if it is worth a separate library, maybe it could just be added to boost/utility ...
thoughts?
This can already be done using the boost range library:
========8<========8<========8<========8<========8<========8<======== #include <boost/range/irange.hpp> #include <boost/range/algorithm/for_each.hpp>
int main() { boost::for_each(boost::irange(0, 10), [] (int) { std::cout << "hello world\n";}); boost::for_each(boost::irange(0, 10), [] (int index) { std::cout << "hello world from " << index << "\n";}); } ========8<========8<========8<========8<========8<========8<========
IMHO, a regular loop looks simpler than either of these variants: for (int i = 0; i < 10; ++i) std::cout << "hello world from " << i << "\n"; also, I guess this should also work: for (auto i: boost::irange(0, 10)) std::cout << "hello world from " << i << "\n"; We could add a new range generator to simplify this code even further and remove the lower bound: for (auto i: boost::times(10)) std::cout << "hello world from " << i << "\n"; where times(n) is equivalent to irange(0, n).