I\'m trying to fill a 2D array on compile time with a given function. Here is my code:
template
struct Table
{
int data[H][W];
//std:
std::array::operator[] since C++14 is constexpr but is also const qualified:
constexpr const_reference operator[]( size_type pos ) const;
^^^^^
Thus you have to cast the arrays to invoke the correct operator[] overload:
template
struct Table
{
//int data[H][W];
std::array, W> data; // This does not work
constexpr Table() : data{} {
for (int i = 0; i < W; ++i)
for (int j = 0; j < H; ++j)
const_cast(static_cast const&>(static_cast, W> const&>(data)[i])[j]) = 10 + j;
}
};
Live Demo
Edit:
As opposed by some people, use of const_cast in such a way does not imply undefined behaviour. In fact as proposed in the proposals for the relaxation of constexpr, it is required by the users to do this work around with const_cast in order to evoke the correct subscript operator overload at least until the issue is resolved in C++17 (see link).