gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:52:02 24 4
gpt4 key购买 nike

在阅读来自 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 代码时了解到,应该避免循环,因为它是运行时的,模板递归是一种替换。

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

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

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

最佳答案

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

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

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

关于c++ - 循环展开和元编程(TMP)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com