简体   繁体   English

关于宏

[英]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 expansion.. 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, eg 常见的是在标头中看到一组宏,其中包含所有常见的扩展,例如


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

PP got it - almost. PP知道了-差不多了。 Abusing the C preprocessor again. 再次滥用C预处理程序。 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)

You may want to look at the boost preprocessor library . 您可能需要查看boost预处理程序库 Especially the BOOST_PP_REPEAT_z macros: 特别是BOOST_PP_REPEAT_z宏:

#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 但我不确定这是一个好主意

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

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