Automatic code generation in C++

你离开我真会死。 提交于 2019-12-07 18:25:07

问题


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.


回答1:


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).




回答2:


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:

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]);
}


来源:https://stackoverflow.com/questions/5291144/automatic-code-generation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!