Re:Tagged unions, or ‘variants’, in C
by comex on Monday June 26, 2017 @10:23AM
(#14637003)
> Not very convincing.
Sorry, I was in a hurry when I wrote that comment :)
The easiest way is to take advantage of the fact that a pointer to a union can be casted to a pointer to one of its members (C11 6.7.2.1.16), or in other words that all the possible variants are at the same offset. So we can do:
typedef struct Some variantof_SomeOne;
#define as(x, T) ((struct T *)variant_cast(x, tag(T), \
offsetof(variantof_##T, u)))
where the definition of Some would have to be changed to give the union field a name, and variant_cast would add the offset given as an argument.
An alternative would be one of the options you mentioned, a boilerplate function. But it doesn't have to be 'real' boilerplate: it's possible to use macros to automate the definition of such functions. Given suitable macros, you can write something like:
Sorry, I was in a hurry when I wrote that comment :)
The easiest way is to take advantage of the fact that a pointer to a union can be casted to a pointer to one of its members (C11 6.7.2.1.16), or in other words that all the possible variants are at the same offset. So we can do:
where the definition of Some would have to be changed to give the union field a name, and variant_cast would add the offset given as an argument.An alternative would be one of the options you mentioned, a boilerplate function. But it doesn't have to be 'real' boilerplate: it's possible to use macros to automate the definition of such functions. Given suitable macros, you can write something like:
and get as much boilerplate as you want, like: