简体   繁体   English

在C ++中自动生成代码

[英]Automatic code generation in C++

I want a piece of code which does not involve loops but automatically generates some C++ code. 我想要一段不涉及循环但自动生成一些C ++代码的代码。

I have an const int d , and from this I want to write d lines of code to access an array. 我有一个const int d ,从这里我想编写d行代码来访问一个数组。 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. 但我不想在for循环中写这个。 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. 提前致谢。

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). 在足够高的优化级别,您的编译器将为您完成,并且可能比您更好,因为优秀的优化编译器将考虑权衡(减少指令缓存局部性,一个)。

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: 如果由于某种原因确实需要这样做,那么在预处理器的帮助下它非常简单:

#include <boost/preprocessor.hpp>

#include <iostream>

void f(int x) { std::cout << x << std::endl; }

int main()
{
    #define MYARRAY_COUNT 10
    int myarray[MYARRAY_COUNT] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    #define GENERATE_ELEMENT_CASE(z, n, data) f(myarray[n]);

    BOOST_PP_REPEAT(MYARRAY_COUNT, GENERATE_ELEMENT_CASE, x)

    #undef GENERATE_ELEMENT_CASE
    #undef MYARRAY_COUNT
}

The expanded main() function looks like: 扩展的main()函数如下所示:

int main()
{
    int myarray[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    f(myarray[0]); f(myarray[1]); f(myarray[2]); f(myarray[3]); f(myarray[4]);
    f(myarray[5]); f(myarray[6]); f(myarray[7]); f(myarray[8]); f(myarray[9]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM