Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take an array reference `T(&)[n]` to the contents of a `std::array<T, n>`

Suppose I have a std::array<T, n> and want to take an array reference to its contents (i.e. to the non-exposed elems array member).

I was surprised to find that std::array<T, n>::data() returns T * and not T (&)[n], so it seems that some kind of cast is necessary. I can write:

std::array<int, 5> arr;
int (&ref)[5] = *reinterpret_cast<int (*)[5]>(arr.data());

However, this looks ugly and potentially unsafe. Is it legitimate (well-defined) code and is there a better way to do this?

like image 705
ecatmur Avatar asked Dec 04 '12 16:12

ecatmur


1 Answers

The standard doesn't provide for the underlying implementation of array, but if it uses int[5] as the underlying representation, then for that implementation only your cast would be (non-portably) legal. For any other underlying representation you violate the strict aliasing rules and enter undefined behavior.

Instead of trying to return the array as an array, can you use iterator pairs to delimit the range you're interested in, following precedent with the standard library?

like image 118
Mark B Avatar answered Sep 30 '22 14:09

Mark B