Treat C cstyle array as std::array

c++

Solution

You cannot do that. The `std::array` is an aggregate and holds its own block of data (as opposed to a pointer to a block of data that can be easily reassigned). So there's no way of avoiding a copy of all the elements. In C++11 this is particularly important because the array's data cannot be moved, so there's no efficient `std::swap` function, for example.

Problem

Is there any safe and standard compliant way to treat a C style array as an std::array without copying the data into a new std::array? This clearly doesn't compile, but is the effect I would like (my real use is more complicated but this short sample should show what I'd like to do). I guess a reinterpret_cast would "work" but probably isn't safe? ``` #include <array> int main() { int data[] = {1, 2, 3, 4, 5}; // This next line is the important one, treating an existing array as a std::array std::array<int, 5>& a = data; } ``` It feels like it ought to be possible as the data should be stored identically. edit: To be clear I don't want to clear a new std::array, I want to refer to the existing data as one.

Original source