Take the array reference `T (&) [n]` to the contents of `std :: array <T, n>`
Suppose I have std::array<T, n> and you want to take a link to its contents (i.e. to an element without an elems object).
I was surprised to find that std::array<T, n>::data() returns T * , not T (&)[n] , so it seems like some sort of selection is needed. I can write:
std::array<int, 5> arr; int (&ref)[5] = *reinterpret_cast<int (*)[5]>(arr.data()); However, it looks ugly and potentially dangerous. Is this a legitimate (well-defined) code, and is there a better way to do this?
The standard does not provide a basic implementation of array , but if int[5] is used as the main representation, then for this implementation only your throw will be (not portable) legal. For any other underlying view, you violate strict alias rules and introduce undefined behavior.
Instead of returning the array as an array, can you use pairs of iterators to delimit the range that you are interested in, after a use-case with the standard library?
An array in C ++ is a defective type (here I'm talking about a c-style array, not std::array ). The reason for this is that the size of the array is not stored anywhere in memory, it is known only at compile time. That's right, when you put an array on another type (usually a pointer), the size of the array is lost.
Now you can see that the inverse transformation cannot be performed because the compiler does not know how to find out the size of the array, looking only at the pointer to the first element. As already mentioned, you can use a couple of iterators instead.