1

How does one properly access the member data and enum symbols when I use an anonymous union? The whole point of the anonymous union was so leave out one level of hierarchy, to make the source code less crufty. I can fix this by naming the union with a type name and member name, but I don't want to do that.

This is VS2012. Surprisingly, the compiler won't take it, but Intellisense does take it!

struct A
{
    struct C {
        enum {M,N,O} bar;
    } c;
    union {
        struct B {
            enum { X,Y,Z} foo;
        } b;
    };
};

void test(void) {
    A a;
    a.c.bar = A::C::M;  // this works
    a.b.foo = A::B::X;  // this doesn't
}

gives these messages

1>test.cpp(85): error C3083: 'B': the symbol to the left of a '::' must be a type
1>test.cpp(85): error C2039: 'X' : is not a member of 'A'
1>          test.cpp(71) : see declaration of 'A'
1>test.cpp(85): error C2065: 'X' : undeclared identifier

Ideally, I want to do this with anonymous/unnamed structs (which does work in some compilers, even though I realize it is not standard C++)

struct A
{
    union {
        struct  {
            enum { X,Y,Z} foo;
            int x;
        } ;
        struct  {
            enum { M,N,O} bar;
            double m;
        } ;
    };
};

void test(void) {
    A a1;
    a1.bar = A::M;
    a1.x = 1;

    A a2;
    a2.foo = A::X;
    a2.m = 3.14;
}
Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
  • [Is it related](http://stackoverflow.com/questions/17637392/anonymous-union-can-only-have-non-static-data-members-gcc-c)? – Gluttton Jun 12 '14 at 20:41
  • @Gluttton - I don't think so – Mark Lakata Jun 12 '14 at 20:42
  • _§ 9.5/5 - The member-specification of an anonymous union shall only define non-static data members. [ Note: Nested types and functions cannot be declared within an anonymous union. — end note ]_ is it related? – Gluttton Jun 12 '14 at 20:46
  • What is it you are trying to do with this? Looks like UB to me. – Red Alert Jun 12 '14 at 20:47
  • @gluttton - I see, it is related. But Visual Studio is not complaining about the nested types, that was not the error message I get. It should complain about the nested type declarations at the point of declaration, not complain that the types don't exist at the point of use. – Mark Lakata Jun 13 '14 at 00:16
  • @RedAlert - I am trying to save memory with the union, but want the overlapped structs to be self-contained. Angew's answer is good enough to get this done -- declare the structs outside the union. – Mark Lakata Jun 13 '14 at 00:17

1 Answers1

3

If I understand your question correctly, this should work:

struct A
{
    struct B {
        enum { X,Y,Z} foo;
        int x;
    };
    struct C {
        enum { M,N,O} bar;
        double m;
    };
    union {
        B b;
        C c;
    };
};
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455