How to make a for loop variable const with the exception of the increment statement?

后端 未结 9 1196
天涯浪人
天涯浪人 2020-12-24 04:26

Consider a standard for loop:

for (int i = 0; i < 10; ++i) 
{
   // do something with i
}

I want to prevent the variable i fr

9条回答
  •  伪装坚强ぢ
    2020-12-24 04:46

    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.

提交回复
热议问题