为什么非const的std ::数组:: operator []的不constexpr? [英] Why is non-const std::array::operator[] not constexpr?
问题描述
我试图填补编译时一个二维数组与给定的功能。这里是我的code:
I'm trying to fill a 2D array on compile time with a given function. Here is my code:
template<int H, int W>
struct Table
{
int data[H][W];
//std::array<std::array<int, H>, W> data; // This does not work
constexpr Table() : data{}
{
for (int i = 0; i < H; ++i)
for (int j = 0; j < W; ++j)
data[i][j] = i * 10 + j; // This does not work with std::array
}
};
constexpr Table<3, 5> table; // I have table.data properly populated at compile time
它工作得很好, table.data code>是正确填充在编译时。
It works just fine, table.data
is properly populated at compile time.
但是,如果我改变普通二维数组 INT [H] [W]
与的std ::阵列&LT;的std ::阵列&LT; INT, H&GT ;, W&GT;
,我在循环体的错误:
However, if I change plain 2D array int[H][W]
with std::array<std::array<int, H>, W>
, I have an error in the loop body:
error: call to non-constexpr function 'std::array<_Tp, _Nm>::value_type& std::array<_Tp, _Nm>::operator[](std::array<_Tp, _Nm>::size_type) [with _Tp = int; long unsigned int _Nm = 3ul; std::array<_Tp, _Nm>::reference = int&; std::array<_Tp, _Nm>::value_type = int; std::array<_Tp, _Nm>::size_type = long unsigned int]'
data[i][j] = i * 10 + j;
^
Compilation failed
显然,我试图调用的std ::数组::运算符[]
,这是不是 constexpr <非const超载/ code>。现在的问题是,为什么它不是
constexpr
?如果C ++ 14允许我们修改 constexpr
的范围,这是为什么不通过的std ::阵列支持
?
Obviously, I'm trying to call non-const overload of std::array::operator[]
, which is not constexpr
. The question is, why it is not constexpr
? If C++14 allows us to modify variables declared in constexpr
scope, why this is not supported by std::array
?
我常想,的std ::阵列
就像普通数组,只有更好。但这里有一个例子,在那里我可以使用普通阵列,但不能使用的std ::阵列
。
I used to think that std::array
is just like plain array, only better. But here is an example, where I can use plain array, but cannot use std::array
.
推荐答案
好吧,这的确是标准的监督。甚至有存在解决这个问题的建议:<一href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0107r0.pdf\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0107r0.pdf
Ok, it is indeed an oversight in the standard. There even exists a proposal to fix this: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0107r0.pdf
[N3598]去掉constexpr成员函数为const的隐性标记。然而,
的std ::阵成员函数这一变化后不重新,导致一个令人惊讶的缺乏
对中的std ::阵列接口constexpr支持。本文通过添加修复了这个疏漏
constexpr到的std ::阵列的成员函数,可以用最小量的支持它
的工作。
[N3598] removed the implicit marking of constexpr member functions as const. However, the member functions of std::array were not revisited after this change, leading to a surprising lack of support for constexpr in std::array’s interface. This paper fixes this omission by adding constexpr to the member functions of std::array that can support it with a minimal amount of work.
这篇关于为什么非const的std ::数组:: operator []的不constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!