开发者

Question about compile time code generation

I have a requirement something like

void doSomeThing(int x)
{
.....
}

void fun()
{

 #ifdef XXXX_1_YYYY
doSomeThing(XXXX_1_YYYY);
 #endif //XXXX_1_YYYY

 #ifdef XXXX_2_YYYY
doSomeThing(XXXX_2_YYYY);
 #endif //XXXX_2_开发者_如何学运维YYYY

 #ifdef XXXX_3_YYYY
 doSomeThing(XXXX_3_YYYY);
 #endif //XXXX_3_YYYY

 #ifdef XXXX_4_YYYY
 doSomeThing(XXXX_4_YYYY);
 #endif //XXXX_4_YYYY

....
upto XXXX_20_YYYY

}

Is there anyway I can reduce the typing of this up to 20 using some macro expansion technique or any other solution?

MACRO definition can be something like this

#define XXXX_1_YYYY 10
#define XXXX_2_YYYY 20
#define XXXX_3_YYYY 30
#define XXXX_4_YYYY 40
...
#define XXXX_20_YYYY 200

Each of the #ifdef are not mutually exclusive. The code is in c++


A trivial answer perhaps, but if they're all mutually exclusive, then using #elif will save you a lot of #endifs.

It's hard to know a good way to avoid this without knowing more about what you're actually trying to do. Are all those functions in the same file, each with a #if around it?


I can't see a way to do it with standard C preprocessor.

Maybe the problem can be restated. Can you can show us broader context?

And remember that, instead of abusing C preprocessor, you can always generate code with some other tool, like m4, perl, bash, etc. Or JScript, VBScript, etc. on Windows. If your build system permits, that is.


If there is a special value of XXXX_n_YYYY (like NULL for a pointer value, -1 for int, etc), you can use that special value to flag that constant as "not defined" (instead of leaving it as undefined). Then you can use some code that looks like:

void fun()
{
    size_t i;
    static XYXX_type job_que[] = { XXXX_1_YYYY, XXXX_2_YYYY, .... };

    for (i=0; i!=ARRAY_SIZE(job_que); ++i)
    {
        if (job_que[i] != SPECIAL_VALUE) do_something(job_que[i]);
    }
}

It is very hard to come up with something better with the given amount of detail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜