如何使用模板元编程展开for循环 [英] How to unroll a for loop using template metaprogramming

查看:168
本文介绍了如何使用模板元编程展开for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写简单的C ++代码,以具有一定展开因子的方式简单地运行for循环? 例如,我需要编写一个for循环,为数组的每个索引分配i的值,即数组大小的A [i] = i可以说1e6.

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.

现在,我想添加一个假设为20的展开因子.我不想手动编写20行代码并将其迭代5k次.我该怎么做呢?我是否嵌套for循环?如果我使用模板元编程,编译器会自动为我展开一些操作吗?以及如何手动设置展开因子(在编译过程中固定)?

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)?

推荐答案

以下示例是用 C ++ 17 编写的,但是采用了一些更详细的技术,该思想适用于C语言. ++ 11及以上.

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

如果您真的想强制展开,请考虑 std::make_integer_sequence 和C ++ 17的折叠表达式:

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;
  });
}

这篇关于如何使用模板元编程展开for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆