I’m porting some old code from C to C++ in Visual Studio 2010 and I came across this:
typedef struct OptionDef {
const char *name;
int flags;
union {
void *dst_ptr;
int (*func_arg)(void *, const char *, const char *);
size_t off;
} u;
const char *help;
const char *argname;
} OptionDef;
static const OptionDef options[] = {
{ "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
...
Which now fails with a syntax error. I’ve seen the response for Statically initialize anonymous union in C++ but overloading the constructors won’t work because I’m setting up an array. Is there any other way of doing this (rather than just rewriting the code not to use a union)?
Update:
I should have been more specific – the array contains different initialisers using all parts of the union:
static int is_full_screen;
{ "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
So just changing the order of the union won’t help.
C++ does not have the
.memberinitialization syntax that C has.You can use aggregate initialization with unions but only on the first member.
Thus, rewrite it with the one you want to set as the first member:
You could also give your struct a constructor – C++11 should allow you to use brace initializers.
Example:
In C++03 you can do it with temporaries if the struct has a constructor: