简体   繁体   English

如何静态初始化包含联合的结构数组?

[英]How can I statically initialise an array of structs containing a union?

I'm porting some old code from C to C++ in Visual Studio 2010 and I came across this: 我正在Visual Studio 2010中将一些旧代码从C移植到C ++,并且遇到了这个问题:

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. 我已经看到了C ++中静态初始化匿名联合的响应,但是重载构造函数将不起作用,因为我正在设置数组。 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 .member initialization syntax that C has. C ++没有C具有的.member初始化语法。

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: 因此,使用您要设置为第一个成员的成员重写它:

union {
    int (*func_arg)(void *, const char *, const char *);
    void *dst_ptr;
    size_t off;
} u;

static const OptionDef options[] = {
    { "x", HAS_ARG, { opt_width }, "force displayed width", "width" },

You could also give your struct a constructor - C++11 should allow you to use brace initializers. 您还可以为您的结构提供构造函数-C ++ 11应该允许您使用括号初始化程序。

Example: 例:

struct foo {
    int flags;
    struct uwrap {
      uwrap(int (*func_arg)(void *, const char *, const char *))
      : func_arg(func_arg) {}
      uwrap(int off)
      : off(off) {}
      union {
          void *dst_ptr;
          int (*func_arg)(void *, const char *, const char *);
          int off;
      };
    } u;
};

int func(void *, const char *, const char *) {}

int main() {
    foo f[] = { { 1, {func}}, { 2, {0}} };
}

In C++03 you can do it with temporaries if the struct has a constructor: 在C ++ 03中,如果该结构具有构造函数,则可以使用临时函数:

foo f[] = { foo(1, func), foo(3, 0) };

Just do this: 只要这样做:

static const OptionDef options[] = {
   { "x", HAS_ARG, {opt_width }, "force displayed width", "width" },
    ...

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

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