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

后端 未结 9 1195
天涯浪人
天涯浪人 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:56

    template
    void while_less(T n, F f, T start = 0){
        for(; start < n; ++start)
            f(start);
    }
    
    int main()
    {
        int s = 0;
        
        while_less(10, [&](auto i){
            s += i;
        });
        
        assert(s == 45);
    }
    

    maybe call it for_i

    No overhead https://godbolt.org/z/e7asGj

提交回复
热议问题