简体   繁体   中英

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.

I want to populate this data into a car array CAR_SUPPORTED[MAX_CARS] such that

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 .

how would I write a macro such that CAR_SUPPORTED[C1] = 1 and so on . 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. Grab example using 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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