简体   繁体   English

使用宏初始化特定的数组元素

[英]initialize specific array elements using macros

I have data file which i want to load during preprocessing .我有我想在预处理期间加载的数据文件。

DATAFILE :
CAR(C1, C2, C3)

There can be n number of cars (C1, C2....Cn), currently 3. The C1,.. are enums fields with specific value say C1=5, C2-8, c3-10.可以有 n 辆汽车 (C1, C2....Cn),目前为 3。C1,.. 是具有特定值的枚举字段,例如 C1=5、C2-8、c3-10。

I want to populate this data into a car array CAR_SUPPORTED[MAX_CARS] such that我想将此数据填充到汽车阵列CAR_SUPPORTED[MAX_CARS] ,以便

CAR_SUPPORTED[C1] = 1 and similarly for C2,C3.. so on.

I tried variadic macro as :我尝试了可变参数宏:

int CAR_SUPPORTED[] ={
#define  CAR(...) __VA_ARGS__};
#include "car.data"

But this could just copy 5, 8 , 10 to 0,1,2 indexes .但这只能将 5, 8 , 10 复制到 0,1,2 索引。

how would I write a macro such that CAR_SUPPORTED[C1] = 1 and so on .我将如何编写一个宏,使得 CAR_SUPPORTED[C1] = 1 等等。 Any suggestions ?有什么建议 ?

Just use array initialization with a designator:只需使用带有指示符的数组初始化:

#define CAR(C1, C2, C3) [C1] = 1, [C2] = 1, [C3] = 1 };

If you which to use that for variadic number of args, I wold use P99 or boost preprocessor macros, or you can write macro expansion yourself.如果您要将其用于可变数量的 args,我会使用P99或 boost 预处理器宏,或者您可以自己编写宏扩展。 Grab example using boost:使用 boost 抓取示例:

#include <boost/preprocessor.hpp>

#define CAR_ONE(r, data, elem)     [elem] = 1,
#define CAR(...) BOOST_PP_SEQ_FOR_EACH(CAR_ONE,,BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) };

CAR(A1, A2, A3)

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

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