David G
David G

Reputation: 96865

Potentially ambiguous statement in §9.5/8

§9.5/9 from the C++11 Standard (emphasis mine):

A union-like class is a union or a class that has an anonymous union as a direct member. A union-like class X has a set of variant members. If X is a union, a non-static data member of X that is not an anonymous union is a variant member of X.

Is the part in bold saying that between a union-like class that is either a class or a union, only if it is a union can it have a non-static variant member that is not an anonymous union? If this is so, why? And what practical difference does it make in code?

I'm actually questioning whether this statement meant to say "If X is a union-like class...". It would make full sense to me then.

Either way, this clause has been bugging me for the past few days and I wish to fully comprehend what it is stating.

Upvotes: 5

Views: 200

Answers (3)

pabdulin
pabdulin

Reputation: 35255

Seems like latest publicly avalable draft (2013-10-13) have a more refined definition, quote:

A union-like class is a union or a class that has an anonymous union as a direct member. A union-like class X has a set of variant members. If X is a union, a non-static data member of X that is not an anonymous union is a variant member of X. In addition, a non-static data member of an anonymous union that is a member of X is also a variant member of X. At most one variant member of a union may have a brace-or-equal-initializer. Example:

union U {
    int x = 0;
    union { };
    union {
        int z;
        int y = 1; // error: initialization for second variant member of U
    };
};

As for the question, the bolded part is actually defines what is a variant member, which a union-like class has to have (by having a union as a direct member) to be a union-like class.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283931

No, your attempted clarification is wrong. Here is a union-like class X:

struct X
{
    int a;
    union {
        double b;
        long c;
    };
};

X::a is a non-static data member of a union-like class X that is not an anonymous union. But it most definitely is NOT a variant member.

All non-static data members of a union are variant members. For union-like classes which are not unions, only those nested within union subobjects are variant members.

Upvotes: 5

paxdiablo
paxdiablo

Reputation: 882716

I feel your pain, it takes many years of cognitive damage caused by looking over standards documents, to be able to correctly parse that sort of stuff.

only if it is a union can it have a non-static variant member that is not an anonymous union?

Not quite.

It's not saying that only the union version of a union-like class can have the non-static blah blah blah.

What it's saying is both can have it (technically, it's not saying that but it's declining to refute the possibility), but only the union version will have it treated as "a variant member of X".

Upvotes: 2

Related Questions