如何在恒定表达式中获取STD阵列大小?
考虑以下代码:
#include <array>
#include <cstddef>
struct A {
std::array<std::size_t, 4> test;
void method() {
std::size_t duptest[test.size()] = {}; // error: variable-sized object may not be initialized
}
};
在评论中的错误下,它失败了。我不明白为什么这被视为VLA,因为test.size
是constexpr
函数。如何停止duptest
被解释为VLA?
Consider this code:
#include <array>
#include <cstddef>
struct A {
std::array<std::size_t, 4> test;
void method() {
std::size_t duptest[test.size()] = {}; // error: variable-sized object may not be initialized
}
};
It fails under Clang with the error in the comment. I don't understand why this is considered a VLA, because test.size
is a constexpr
function. How do I stop duptest
from being interpreted as a VLA?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
test
表示this-&gt; test
,评估this.size()
必须首先评估this-&gt; test
。但是此
不是常数的表达式,所以test.size()
也不是恒定的表达式constexpr
,并且不使用test
。因此,这是VLA,是非标准的。您可以使用
std :: Tuple_size
。test
meansthis->test
, and evaluatingthis.size()
must first evaluatethis->test
. Butthis
is not a constant expression sotest.size()
is not a constant expression, even thoughstd::array::size
isconstexpr
and it doesn't usetest
. Therefore this is a VLA and is nonstandard.You might use
std::tuple_size
.问题是表达式
test.size()
等效于this-&gt; test.size()
,但对象更多是一个运行时构建体。特别是,在标准C ++中,数组的大小必须是一个编译时常数(aka 常数expression ),expression
this-&gt; test.size()
is不是。来自 expr.const#2 :现在在您的示例中,
此
出现在成员函数方法
中正在作为表达式this-&gt; test.size()
进行评估。因此,
this-&gt; test.size()
不能用于指定数组的大小,因为该表达式不是编译时常数。The problem is that the expression
test.size()
is equivalent tothis->test.size()
but thethis
object is more of a run-time construct. In particular, in standard C++ the size of an array must be a compile-time constant(aka constant expression) which the expressionthis->test.size()
is not. From expr.const#2:Now in your example,
this
appears inside the member functionmethod
but the member functionmethod
is neither constexpr nor it is being evaluated as part of the expressionthis->test.size()
.Therefore
this->test.size()
cannot be used to specify the size of the array since that expression is not a compile-time constant.