I would like to do something like
std::array<int, 5> array1 = {{ ... }};
const std::array<int, 3>& array2 = array1[1:4]; // [x:y] doesn't exist
That is, get an array that is a sort of view of another array, without having to copy it.
I would like to do something like
std::array<int, 5> array1 = {{ ... }};
const std::array<int, 3>& array2 = array1[1:4]; // [x:y] doesn't exist
That is, get an array that is a sort of view of another array, without having to copy it.
No, you can't do that. All standard library containers are unique owners of their data, and std::array is no exception. In fact, std::array is constrained to be implemented in such a way so that the elements are stored inside an actual array member of the class, which would make aliasing impossible.
There is a proposal for an array_view class that would represent a non-owning view into a contiguous block of data. You can read about it here. I don't know the status of this proposal (the current C++ standardization process confuses me).
You can if you use valarray instead of array http://en.cppreference.com/w/cpp/numeric/valarray/slice
Edit: from C++20 you can refer to a continuous sub-array with std::span
Yes you can, std::span in C++20 provides a view over a contiguous sequence of objects.
std::array<int, 5> array1 = {20, 10, 35, 30, 5};
std::span array2(array1.begin(), array1.begin() + 3); // {20, 10, 35}; subview of array1
The underlying data is not copied but rather referenced, therefore care should be taken to ensure the original array still exists when using the span.
std::array<int, 3>& array2 = reinterpret_cast<std::array<int, 3>&>(array1);
std::array wrapping a C-style array (in which case I am not convinced there is an aliasing violation) but the standard doesn't require thatclang or gcc to produce a strict aliasing warning when using std::array. Perhaps there is something special about the internal representation of std::array<T,N> as T[N] that makes it work. I am talking about this code for example std::array<int,3> aa = {{1,2,3}}; std::array<int,2>& ee = reinterpret_cast<std::array<int,2>&>(aa[1]); assert(ee[0] == 2);