Very pedantic: Is "friend" allowed in anonymous unions?

60 views
Skip to first unread message

Myriachan

unread,
May 4, 2015, 11:28:22 PM5/4/15
to std-dis...@isocpp.org
Are anonymous unions allowed to declare friends, despite being pointless, given that all members must be public?

clang 3.6.0 doesn't allow it for either classes or functions; GCC 5.1.0 and MSVC 14.0 are fine with it.  I don't see anything in the Standard prohibiting it.  All 3 compilers correctly require all members to be public; none care about the redundant "public:" access-specifier, either.

I'm wondering because this seems like a silly corner case of clang......or the Standard. =P


#include <cstdio>

static union
{
private:  // correctly allowed by all 3 compilers because no members declared
public:
   
unsigned s_u;
   
float s_f;
   
friend int main();
   
friend class Meow;
};
static_assert(sizeof(s_u) == sizeof(s_f), "size mismatch");

class Meow { };

int main()
{
    s_f
= 1.0f;
    std
::printf("%08X\n", s_u);
   
return 0;
}




Melissa

David Krauss

unread,
May 4, 2015, 11:44:08 PM5/4/15
to std-dis...@isocpp.org
On 2015–05–05, at 11:28 AM, Myriachan <myri...@gmail.com> wrote:

I don't see anything in the Standard prohibiting it.

[class.union] §9.5/5: “Each member-declaration in the member-specification of an anonymous union shall either define a non-static data member or be a static_assert-declaration.”

“Member-declaration” is italicized, suggesting that it refers to the grammar production and not to declarations that declare members.

All 3 compilers correctly require all members to be public; none care about the redundant "public:" access-specifier, either.

Not granting access specifically within an anonymous union I can understand, but I wonder why variant members of the same union can’t have different access specifiers?

Columbo

unread,
May 5, 2015, 2:56:12 PM5/5/15
to std-dis...@isocpp.org
 none care about the redundant "public:" access-specifier, either.

How is it redundant given that, if we remove it, the members are private?

Myriachan

unread,
May 5, 2015, 3:08:08 PM5/5/15
to std-dis...@isocpp.org
On Tuesday, May 5, 2015 at 11:56:12 AM UTC-7, Columbo wrote:
 none care about the redundant "public:" access-specifier, either.

How is it redundant given that, if we remove it, the members are private?

An earlier version of the email didn't have that private: line.  Sorry about the confusion with that statement.

David Krauss's email explained this for me; it's Visual Studio and GCC that are wrong, and clang is right.  Having access-specifiers, even private:, is fine, since access-specifiers aren't member-specifications.  But once you have a member-specification, it has to be a non-static data member, and it must be public.

Melissa
Reply all
Reply to author
Forward
0 new messages