我想在编译时展开下面的嵌套循环。我在每个'for‘循环后都有一些代码和一个条件,如下面的代码片段所示。我找到了使用模板元编程在嵌套的“for”循环之间展开它而不需要任何代码(和条件)的方法,但这对我的用例没有帮助。我正在为我下面的例子寻找一种方法。我真的很感谢你的帮助!
for (i=0;i<2;i++)
{
//some code
if (some condition using i)
{
for(j=0;j<12;j++)
{
//some code
if (another condition using j)
{
for(k=0;k<10;k++)
{
//some code
}
}
}
}
}
发布于 2020-10-01 15:33:49
编译与优化(如-O3 -march=native
),编译器不仅会展开,但转置,向量化,有时甚至完全消除你的循环。
为确保代码质量,请定期检查生成的关键代码汇编,例如在https://gcc.godbolt.org/上。
发布于 2020-10-01 15:15:43
我把支持自定义增量和起始值的挑战留给了您。如果您的条件是运行时,只需将N传递给F并在lambda中实现该条件。
这更多的是一个模板演示,我同意rustyx的观点。让编译器为你优化它。
#include <iostream>
template<unsigned N>
struct IsOdd
{
static constexpr bool value = N % 2 == 0;
};
template<unsigned N, typename F, template <unsigned> typename Condition>
struct RepeatIfHelper
{
void operator()(F f)
{
if constexpr(Condition<N>::value)
{
f();
}
RepeatIfHelper<N-1, F, Condition>()(f);
}
};
template<typename F, template <unsigned> typename Condition>
struct RepeatIfHelper<0, F, Condition>
{
void operator()(F f)
{
if constexpr(Condition<0>::value)
{
f();
}
}
};
template<unsigned N, template <unsigned> typename Condition, typename F>
void RepeatIf(F f)
{
RepeatIfHelper<N, F, Condition>()(f);
}
int main()
{
RepeatIf<7, IsOdd>([](){
RepeatIf<5, IsOdd>([](){
RepeatIf<3, IsOdd>([](){
std::cout << "Hi" << std::endl;
});
});
});
}
发布于 2020-10-01 15:06:26
在简单的情况下,编译器会代替你来做这件事。但是可以使用编译器指令#pragma unroll
。这篇文章可能会有帮助- What does #pragma unroll do exactly? Does it affect the number of threads?
https://stackoverflow.com/questions/64158095
复制相似问题