循环展开和元编程(TMP)?

loop unrolling and metaprogramming(TMP)?

在从 wikipedia' article-Template metaprogramming 读取 [编译时代码优化] 时:

template <int length>
Vector<length>& Vector<length>::operator+=(const Vector<length>& rhs) 
{
    for (int i = 0; i < length; ++i)
        value[i] += rhs.value[i];
    return *this;
}

When the compiler instantiates the function template defined above, the following code may be produced:[citation needed]

template <>
Vector<2>& Vector<2>::operator+=(const Vector<2>& rhs) 
{
    value[0] += rhs.value[0];
    value[1] += rhs.value[1];
    return *this;
}

The compiler's optimizer should be able to unroll the for loop because the template parameter length is a constant at compile time.

However, take caution as this may cause code bloat as separate unrolled code will be generated for each 'N'(vector size) you instantiate with.

但是,我在编写 TMP 代码时了解到,应该避免循环,因为它是 运行 时间,并且模板递归是一个替换。

我在 google 上搜索编辑并找到 this question 手动展开。答案也鼓励使用递归。

那么,我应该依靠编译时代码优化,它能够在编译时使用编译时确定长度(循环结束)展开 for 循环,还是一直使用递归?

我认为来自维基百科的文章鼓励我们依赖 un-roll。可能是我理解错了?

根据我的经验,循环展开可以达到一定长度。我想如果代码变得太大,这会对缓存产生负面影响并导致性能达不到最佳水平

循环展开与模板无关(至少在一般情况下)。当大小已知时,编译器可以展开循环(它们也可以展开非静态有界循环,但这要困难得多)。

如果您使用模板递归,那仅意味着您可以控制循环展开的方式。

无论如何,不​​要尝试过早优化...滚动循环不太可能是您的运行时成本问题。让编译器展开至少是免费的,而自己做有点痛苦和容易出错,而且不确定结果是否值得。