3

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.

Community
  • 1
  • 1
Tudor Berariu
  • 4,910
  • 2
  • 18
  • 29
  • Your casting seems... suspect. Why do you want that? This question seems to be [an XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Some programmer dude Apr 02 '15 at 15:37
  • I have several different types (machine learning models) that have a large set of parameters. In order to use its own parameters efficiently, each type holds them packed in one or more multi-dimensional arrays. Separately I have a generic function that optimizes any number of parameters regardless of the model they come from. – Tudor Berariu Apr 02 '15 at 15:43
  • 1
    Mind the strict aliasing rule. – Lingxi Apr 02 '15 at 15:51

1 Answers1

4

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Oh... sure. I just didn't see it. Thanks for your time. Yes, I will allow the template instantiation only if `is_standard_layout`. – Tudor Berariu Apr 02 '15 at 15:55