lundi 2 mars 2015

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

Consider the following piece of code:



struct S
{
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. I am curious what is the correct behavior here. Maybe should I explicitly state that arr2 size is sizeof(int) * N?


Aucun commentaire:

Enregistrer un commentaire