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

后端 未结 9 1153
天涯浪人
天涯浪人 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 05:04

    From c++20, you can use ranges::views::iota like this:

    for (int const i : std::views::iota(0, 10))
    {
       std::cout << i << " ";  // ok
       i = 42;                 // error
    }
    

    Here's a demo.


    From c++11, you can also use the following technique, which uses an IIILE (immediately invoked inline lambda expression):

    int x = 0;
    for (int i = 0; i < 10; ++i) [&,i] {
        std::cout << i << " ";  // ok, i is readable
        i = 42;                 // error, i is captured by non-mutable copy
        x++;                    // ok, x is captured by mutable reference
    }();     // IIILE
    

    Here's a demo.

    Note that [&,i] means that i is captured by non-mutable copy, and everything else is captured by mutable reference. The (); at the end of the loop simply means that the lambda is invoked immediately.

提交回复
热议问题