Very simply, is there a simpler way to repeat a block for a certain number of times, where the block inside does not need the counter variable? The trivial solution is of course
for (int i = 0; i < repetitions; ++i) {
//do your thing, i is not used here
}
However, now that we have ranged for, standard algorithms and other fancy constructs for iterating over containers, in comparison this is actually starting to feel like a lot of boilerplate and details for what should be an even simpler case. For example we're not interested in the variable i
at all etc.
The closest thing to a concrete problem is this: when I encounter a for loop such as above, I need to scan through the code block to see if i
is actually used, or if it's just a dummy counter. The declaration of a for loop which actually wants to do something with the integers 0 to repetitions - 1
will look identical. So a repeat (n)
-type construct would have the extra semantic information that all the iterations will be the same, except for potential side-effects.
One option is to make a template
template<class functor>
repeat(functor fun, unsigned n) {
for (unsigned i = 0; i < n; ++i)
fun();
}
and call
repeat([&](){
//do your thing
}, repetitions)
but this really seems like overengineered overkill for a simple problem. This could be macroized to make the usage a bit nicer, but that certainly won't help with the overengineered feel.
So one valid answer is that I'm on a wild goose chase here, and should just use the good old for loop with counter.
Any standard C++ is fine, including upcoming standards.
Related questions such as How to create a loop in C++ that loops a certain amount of times? and How to create a loop in C++ that loops a certain amount of times? are beginners asking for some way to achieve this, whereas I'm specifically asking for a modern, clean and elegant way to achieve this. c++ repeat N iterations is very close, though the difference here is that I'm asking for any alternatives, not necessarily included in std::
.