gpt4 book ai didi

c++ - 通过引用调用 constexpr 方法 - 结果是常量表达式吗?

转载 作者:可可西里 更新时间:2023-11-01 18:31:06 25 4
gpt4 key购买 nike

下面的代码

#include <array>

void foo(const std::array<int, 42> &a)
{
constexpr size_t S = a.size();
}

int main() {}

在 GCC 中编译正常,但在 clang 中编译失败并出现以下错误消息

main.cpp:5:28: error: constexpr variable 'S' must be initialized by a constant expression
constexpr size_t S = a.size();
^~~~~~~~

与此同时,许多关于 SO 上的 constexpr 问题的帖子似乎暗示 clang 通常对 constexpr 有更好的(更迂腐?)支持。那么,在这种情况下哪个编译器是正确的?

请注意,一旦引用参数替换为按值传递参数,两个编译器都会很乐意接受代码。

最佳答案

[expr.const]/2 :

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following expressions:

  • [...]
  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either

    • it is initialized with a constant expression or
    • its lifetime began within the evaluation of e;
  • [...]

评估 a.size() 评估 id-expression a,它“指的是一个变量......引用类型”并且没有预先初始化。因此它不是核心常量表达式,因此也不是常量表达式。

关于c++ - 通过引用调用 constexpr 方法 - 结果是常量表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com