Tudor Berariu
Tudor Berariu

Reputation: 4910

reinterpret_cast structure to a fixed size array

I have a structure S that packs together two fixed size arrays of type T.

template<typename T>
struct S {
    array<array<T, 20>, 10> x1;
    array<T, 10> x2;
};

I want to get a reference to a uni-dimensional array of elements of type T of size 210. I tried to use reinterpret_cast, but the compiler won't accept this:

S<T> s;
array<T, 210>& x = *reinterpret_cast<S*>(&s);

I know this works:

  S<T> s;
  T* x = reinterpret_cast<T*>(&s);

but is there a way to get a reference to a fixed size unidimensional array from that structure? I tried using #pragma pack(pop, 1) with no success.

Upvotes: 3

Views: 1655

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254451

reinterpret_cast<array<T, 210>&>(s) should do that, if that's really what you want.

It should be well-defined, since these are standard layout types (assuming that T is). But you're skating on thin ice.

Upvotes: 4

Related Questions