Home > Blockchain >  How to make a template cycle?
How to make a template cycle?

Time:07-25

I'm very often fiddling with cycle and they're almost the same, I think you can simplify a lot of code if you have one template.

// the blocks can be different, but the number is known before compilation
const int block_1 = 10,
          block_2 = 4,
          block_3 = 6,
          block_4 = 3;

Basically all cycles are like this

the cycle can be like this

for (int i = 1; i < block_1 - 1;   i) {

}

or this

for (int i = 1; i < block_1 - 1;   i) {
    for (int k = 1; k < block_2 - 1;   k) {

    }
}

or this

for (int i = 1; i < block_1 - 1;   i) {
    for (int k = 1; k < block_2 - 1;   k) {
        for (int j = 1; j < block_3 - 1;   j) {
          

        }
    }
}

The number of cycle within a cycle can be a lot, but they are similar.

I think that if I use a template instead of loops all the time, would it be more convenient or not, but maybe I shouldn't and you will dissuade me from doing it.

Ideally I would like a template like this

for_funk(block_1, block_2, block_3) {
   // Here I write the code that will be inside the three loops block_1, block_2, block_3
}

Maybe this will help https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2374r4.html

CodePudding user response:

Yes, you can compose iota_view and cartesian_product_view to get nested indexes in C 23

constexpr inline auto for_funk = [](auto... index) {
  return std::views::cartesian_product(std::views::iota(1, index-1)...);
};

const int block_1 = 10,
          block_2 = 4,
          block_3 = 6,
          block_4 = 3;
for (auto [i, j, k, w] : for_funk(block_1, block_2, block_3, block_4))
  // use i, j, k, w

Demo with range-v3

  • Related