Consider a standard for loop:
for (int i = 0; i < 10; ++i)
{
// do something with i
}
I want to prevent the variable i
fr
One simple approach not yet mentioned here that works in any version of C++ is to create a functional wrapper around a range, similar to what std::for_each
does to iterators. The user is then responsible for passing in a functional argument as a callback which will be invoked on each iteration.
For example:
// A struct that holds the start and end value of the range
struct numeric_range
{
int start;
int end;
// A simple function that wraps the 'for loop' and calls the function back
template
void for_each(const Fn& fn) const {
for (auto i = start; i < end; ++i) {
const auto& const_i = i;
fn(const_i);
}
}
};
Where the use would be:
numeric_range{0, 10}.for_each([](const auto& i){
std::cout << i << " "; // ok
//i = 100; // error
});
Anything older than C++11 would be stuck passing a strongly-named function pointer into for_each
(similar to std::for_each
), but it still works.
Here's a demo
Although this may not be idiomatic for for
loops in C++, this approach is quite common in other languages. Functional wrappers are really sleek for their composability in complex statements and can be very ergonomic for use.
This code is also simple to write, understand, and maintain.