如何在C ++中展开短循环 [英] How to unroll a short loop in C++

查看:79
本文介绍了如何在C ++中展开短循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何获得这样的东西:

I wonder how to get something like this:

copy(a, b, 2, 3)

  • 然后得到

  • And then get

    a[2] = b[2];
    a[3] = b[3];
    a[4] = b[4];
    

  • 我知道C #defines不能递归使用以获得这种效果.但是我使用的是C ++,所以我认为模板元编程可能是合适的.

    I know that C #defines can't be used recursively to get that effect. But I'm using C++, so I suppose that template meta-programming might be appropriate.

    我知道有一个 Boost 库,但我只想要这种简单"的技巧,而Boost太混乱".

    I know there is a Boost library for that, but I only want that "simple" trick, and Boost is too "messy".

    推荐答案

    对此最简单的解决方案是编写一个循环,在该循环中,开始值和结束值是已知的:

    The most straightforward solution to this is to write a loop where the start and end values are known:

    for(int i = 2; i <= 4; i++) {
      a[i]=b[i]; 
    }
    

    我认为这比任何种类的模板/运行时调用混合物都更好:编写的循环对于编译器的优化器是完全清楚的,并且没有层次的函数调用可以深入了解正在发生的事情.

    I think this is better than any sort of template/runtime-call mixture: The loop as written is completely clear to the compilers' optimizer, and there are no levels of function calls to dig through just to see what's going on.

    这篇关于如何在C ++中展开短循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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