开发者

Regarding macros

i was looking for macro which can expand like the following:

FILL_BUFF(4) should be expanded as (0xFF, 0xFF, 0xFF, 0xFF)... what can be the macro written for the above ex开发者_JS百科pansion..


PP got it - almost. Abusing the C preprocessor again. On the other hand, it deserves nothing better.

#define FILL_BUFF(N) FILL_BUFF_ ## N

#define FILL_BUFF_1 (0xFF)
#define FILL_BUFF_2 (0xFF,0xFF)
#define FILL_BUFF_3 (0xFF,0xFF,0xFF)
#define FILL_BUFF_4 (0xFF,0xFF,0xFF,0xFF)


Macros don't have conditional controls such as loops - they are very simple.

It's common to see a group of macros in a header covering all the common expansions, e.g.


#define FILL_BUFF_1 (0xFF)
#define FILL_BUFF_2 (0xFF,0xFF)
#define FILL_BUFF_3 (0xFF,0xFF,0xFF)
#define FILL_BUFF_4 (0xFF,0xFF,0xFF,0xFF)


You may want to look at the boost preprocessor library. Especially the BOOST_PP_REPEAT_z macros:

#define DECL(z, n, text) text ## n = n;

BOOST_PP_REPEAT(5, DECL, int x)

results in:

int x0 = 0; int x1 = 1; int x2 = 2; int x3 = 3; int x4 = 4;

In your case you could do:

#define FILL_BUFF_VALUE(z, n, text) text,
#define FILL_BUFF(NPLUSONE, VALUE) { BOOST_PP_REPEAT(NPLUSONE, FILL_BUFF_VALUE, VALUE } VALUE )

int anbuffer[] = FILL_BUFF(4 /* +1 */,0xff); // anbuffer will have length 5 afterwards

which would expand to

int anbuffer[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };


Hmm, maybe via memset:

#define FILL_BUFF(buf, n) memset(buff, 0xff, n)

But I am not sure that is such a good idea

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜