Why are designated initializers not implemented in g++

让人想犯罪 __ 提交于 2019-11-28 09:53:42

As I noted in a comment, G++ doesn't support C99 standard designated initialisers, but it does support the GNU extension to C90 which allows designated initialisers. So this doesn't work:

union value_t {
    char * v_cp;
    float v_f;
};
union value_t my_val = { .v_f = 3.5f };

But this does:

union value_t my_val = { v_f: 3.5f };

This seems to be a bad interaction of co-ordination between the C and C++ standards committees (there is no particularly good reason why C++ doesn't support the C99 syntax, they just haven't considered it) and GCC politics (C++ shouldn't support C99 syntax just because it's in C99, but it should support GNU extension syntax that achieves exactly the same thing because that's a GNU extension that can be applied to either language).

I ran into this same problem today. g++ with -std=c++11 and c++14 does support designated initializers, but you can still get a compilation error "test.cxx:78:9: sorry, unimplemented: non-trivial designated initializers not supported" if you don't initialize the struct in the order in which it's members have been defined. As an example

struct x
{
    int a;
    int b;
};

// This is correct
struct x x_1 = {.a = 1, .b = 2};
// This will fail to compile with error non-trivial designated initializer
struct x x_2 = {.b = 1, .a = 2};

C++ does not support this. It will not even be in the C++0x standards it seems: http://groups.google.com/group/comp.std.c++/browse_thread/thread/8b7331b0879045ad?pli=1

Also, why are you trying to compile the Linux kernel with G++?

As of at least g++-4.8 this is now supported by default.

What about anonymous unions?

In C I can have this:

struct vardir_entry {
    const uint16_t id;
    const uint8_t sub;
    const char *name;
    const uint8_t type;

    const union {   
        struct vardir_lookup lookup;
        struct vardir_min_max_conf minmax;       
    };

    const union {
        const struct vardir_value_target_const const_value;
        const struct vardir_value_target value;
    };
};

And initialized like this:

static const struct vardir_entry _directory[]{
        { .id = 0xefef, .sub = 0, .name = "test", .type = VAR_UINT32, .minmax = { .min = 0, .max = 1000 }, .value = VARDIR_ENTRY_VALUE(struct obj, &obj, member) }
    };

However under g++ even with c++14 this gives the same "sorry, unimplemented" error. We do need to be able to define C variables in C++ when we at least want to unit test C code with C++ test framework. The fact that such a valuable feature from C is not being supported is quite a shame.

It will be officially supported in C++20, and is already implemented in g++8.2 (even without the std=c++2a flag).

Accoding to http://gcc.gnu.org/c99status.html designated initializers have been already implemented.

What version of g++ do you use? (Try g++ -- version)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!