如何在恒定表达式中获取STD阵列大小?

发布于 2025-01-24 08:21:59 字数 1821 浏览 1 评论 0原文

考虑以下代码:

#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
    }
};

godbolt clang

在评论中的错误下,它失败了。我不明白为什么这被视为VLA,因为test.sizeconstexpr函数。如何停止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
    }
};

Godbolt Clang

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以歌曲疗慰 2025-01-31 08:21:59

test表示this-&gt; test,评估this.size()必须首先评估this-&gt; test。但是不是常数的表达式,所以test.size()也不是恒定的表达式constexpr,并且不使用test。因此,这是VLA,是非标准的。

您可以使用std :: Tuple_size

size_t duptest[std::tuple_size<decltype(test)>()] = {};

test means this->test, and evaluating this.size() must first evaluate this->test. But this is not a constant expression so test.size() is not a constant expression, even though std::array::size is constexpr and it doesn't use test. Therefore this is a VLA and is nonstandard.

You might use std::tuple_size.

size_t duptest[std::tuple_size<decltype(test)>()] = {};
慕巷 2025-01-31 08:21:59

问题是表达式test.size()等效于this-&gt; test.size(),但对象更多是一个运行时构建体。特别是,在标准C ++中,数组的大小必须是一个编译时常数(aka 常数expression ),expression this-&gt; test.size() is不是。来自 expr.const#2

表达式e是核心常数表达式>

  • this,除了constexpr函数或的constexpr构造函数外,该构建器是e ;
  • 的一部分进行评估的。;

现在在您的示例中,出现在成员函数方法中正在作为表达式this-&gt; test.size()进行评估。

因此,this-&gt; test.size()不能用于指定数组的大小,因为该表达式不是编译时常数。

The problem is that the expression test.size() is equivalent to this->test.size() but the this 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 expression this->test.size() is not. From expr.const#2:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

  • this, except in a constexpr function or a constexpr constructor that is being evaluated as part of e;

Now in your example, this appears inside the member function method but the member function method is neither constexpr nor it is being evaluated as part of the expression this->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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文