C++ 中的自动代码生成
我想要一段不涉及循环但自动生成一些C++代码的代码。
我有一个 const int d,我想从中编写 d 行代码来访问数组。例如
for(int k=0; k<d;++k){
// do something to myarryay[k];
}
,但我不想将其写在 for 循环中。我希望编译器像编写以下代码行一样执行:
do something to myarray[0]
do something to myarray[1]
.
.
.
do something to myarray[d]
任何人都可以给我一些执行此操作的代码的建议吗?
提前致谢。
I want a piece of code which does not involve loops but automatically generates some C++ code.
I have an const int d
, and from this I want to write d lines of code to access an array. So for instance
for(int k=0; k<d;++k){
// do something to myarryay[k];
}
but I don't want to write this in a for loop. I want the complier to execute as if the following lines of code was written:
do something to myarray[0]
do something to myarray[1]
.
.
.
do something to myarray[d]
Can anyone give me a suggestion on some code that does this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定需要手动执行此操作吗?这是一种称为循环展开的优化。在足够高的优化级别下,您的编译器将为您完成此操作,并且可能比您做得更好,因为良好的优化编译器会考虑权衡(其中之一是减少指令缓存局部性)。
Are you sure you need to do this manually? This is an optimization known as loop unrolling. At high enough optimization levels, your compiler will do it for you, and possibly better than you can, since a good optimizing compiler will take into account the tradeoffs (reduced instruction cache locality, for one).
您应该很少需要手动展开循环(我想说永远不会,但如果您正在处理具有疯狂性能要求的东西并且您认为可以提高编译器优化器,那么也许您可以手动展开循环)。
如果由于某种原因您确实需要这样做,那么在预处理器的帮助下,这非常简单:
扩展的
main()
函数如下所示:You should rarely need to manually unroll a loop (I'd say never, but if you're working on something with crazy performance requirements and you think you can one-up the compiler optimizer, then perhaps you might manually unroll a loop).
If you do need to do this for some reason, it's quite straightforward with the help of the preprocessor:
The expanded
main()
function looks like: