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.

3
  • Your casting seems... suspect. Why do you want that? This question seems to be an XY problem. Commented Apr 2, 2015 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. Commented Apr 2, 2015 at 15:43
  • 1
    Mind the strict aliasing rule. Commented Apr 2, 2015 at 15:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh... sure. I just didn't see it. Thanks for your time. Yes, I will allow the template instantiation only if is_standard_layout<T>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.