Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unroll a for loop using template metaprogramming

How do you write a simple C++ code to simply run a for loop with a certain unrolling factor? For instance, I need to write a for loop that assigns a value of i to each index of the array, i.e, A[i]=i for array size lets say 1e6.

Now I want to add an unrolling factor of lets say 20. I do not want to manually write 20 lines of code and iterate it 5k times. How do I do this? Do I nest my for loop? Does the compiler automatically do some unrolling for me if I use template metaprogramming? And how do I manually set an unrolling factor (fixed at compile time ofcourse)?

like image 690
Pankaj Kumar Avatar asked Oct 22 '17 06:10

Pankaj Kumar


1 Answers

The following examples are written in C++17, but with some more verbose techniques the idea is applicable to C++11 and above.

If you really want to force some unrolling then consider std::make_integer_sequence and C++17's fold expressions:

#include <iostream>
#include <type_traits>
#include <utility>

namespace detail {

template<class T, T... inds, class F>
constexpr void loop(std::integer_sequence<T, inds...>, F&& f) {
  (f(std::integral_constant<T, inds>{}), ...);// C++17 fold expression
}

}// detail

template<class T, T count, class F>
constexpr void loop(F&& f) {
  detail::loop(std::make_integer_sequence<T, count>{}, std::forward<F>(f));
}

int main() {
  loop<int, 5>([] (auto i) {
    constexpr int it_is_even_constexpr = i;
    std::cout << it_is_even_constexpr << std::endl;
  });
}
like image 55
Julius Avatar answered Sep 21 '22 07:09

Julius