nick
nick

Reputation: 862

how to define a variadic macro to initalize a union?

I want to define a lot of union like this:

union {
  float a;
  float b;
  float c;  // there can be many variables
} a;

i dont want to make code be too large

so i want to define a macro to slove this.

the ideal macro looks like:

#define U(real_name, ...)/
union {\
....

and i just need one line to define:

U(a, b, c, d)

but i dont know how to get the variadic element from ..., can you help on this?

Upvotes: 0

Views: 178

Answers (1)

kakkoko
kakkoko

Reputation: 321

Try this:

#define SIZEOF_VA_ARGS(...) SIZEOF_VA_ARGS_(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define SIZEOF_VA_ARGS_(_1, _2, _3, _4, _5, N, ...) N

#define U_1(type, memb)      type memb
#define U_2(type, memb, ...) type memb; U_1(type, __VA_ARGS__)
#define U_3(type, memb, ...) type memb; U_2(type, __VA_ARGS__)
#define U_4(type, memb, ...) type memb; U_3(type, __VA_ARGS__)
#define U_5(type, memb, ...) type memb; U_4(type, __VA_ARGS__)

#define CONCAT(a, b)  a##b
#define U_(N, type, ...) CONCAT(U_, N)(type, __VA_ARGS__)

#define U(...) \
    union { U_(SIZEOF_VA_ARGS(__VA_ARGS__), float, __VA_ARGS__); }
U(a, b, c, d) foo;
// or
using mytype = U(a, b, c, d);
mytype foo;

Note that the above code only supports a maximum of five members, so if you want to use more than five members, you will need to define U_6, U_7, ..., and insert numbers to the definition of SIZEOF_VA_ARGS/SIZEOF_VA_ARGS_.

Upvotes: 1

Related Questions