C++ union element size based on other's element size

49 views
Skip to first unread message

piot...@gmail.com

unread,
Mar 2, 2015, 7:26:41 PM3/2/15
to std-dis...@isocpp.org
Recently I have come across some discrepancies between gcc and clang. Consider the following piece of code:
struct S
{
    union
    {
        int arr1[10];
        char arr2[sizeof(arr1)];
    };
};

It compiles successfully with gcc 4.9.2 in c++03 and c++11 mode. However when I change S to be a template like so:

template <size_t N>
struct S
{
    union
    {   
        int arr1[N];
        char arr2[sizeof(arr1)];
    };  
};

I get the following error output:

error: int S<10ul>::<anonymous union>::arr1 [10]’ is inaccessible

int arr1[N];

error: within this context

char arr2[sizeof(arr1)];

Clang compiles both versions only in c++11 mode. Is this a legal piece of code? There is an open question on this particular problem on stackoverflow. Some people quoted the standard however none of them seem to give a definitive answer.

Thanks,

Piotr

Richard Smith

unread,
Mar 2, 2015, 8:13:46 PM3/2/15
to std-dis...@isocpp.org
On Mon, Mar 2, 2015 at 4:26 PM, <piot...@gmail.com> wrote:
Recently I have come across some discrepancies between gcc and clang. Consider the following piece of code:
struct S
{
    union
    {
        int arr1[10];
        char arr2[sizeof(arr1)];
    };
};

It compiles successfully with gcc 4.9.2 in c++03 and c++11 mode. However when I change S to be a template like so:

template <size_t N>
struct S
{
    union
    {   
        int arr1[N];
        char arr2[sizeof(arr1)];
    };  
};

I get the following error output:

error: int S<10ul>::<anonymous union>::arr1 [10]’ is inaccessible

int arr1[N];

error: within this context

char arr2[sizeof(arr1)];

Clang compiles both versions only in c++11 mode. Is this a legal piece of code?

This is ill-formed in C++98/C++03 due to the use of the non-static data member 'arr1' outside of a member function. It is valid in C++11, in either templated or non-templated form.

There is an open question on this particular problem on stackoverflow. Some people quoted the standard however none of them seem to give a definitive answer.

Thanks,

Piotr

--

---
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-discussio...@isocpp.org.
To post to this group, send email to std-dis...@isocpp.org.
Visit this group at http://groups.google.com/a/isocpp.org/group/std-discussion/.

piot...@gmail.com

unread,
Mar 3, 2015, 3:22:27 AM3/3/15
to std-dis...@isocpp.org
Can you please provide a quote from the standard explaining what you said in your email?

Thank,
Piotr
Reply all
Reply to author
Forward
0 new messages