【发布时间】:2021-03-22 03:39:44
【问题描述】:
(这是对this问题的跟进。)
所以我想专门问一个问题,以了解我收到的that answer中引用的标准,而我的确切问题在标题中。
老实说,即使在cppreference 上,我也无法理解为什么标准如此规定的原因。
但是,这是一个最小的例子:
#include <array>
int main() {
auto arr = std::array<int,3>{{1,2,3}};
constexpr auto size1 = arr.size(); // OK
auto const& array = arr;
constexpr auto size2 = array.size(); // does not compile
}
编译不报错(报错信息与-std=11/14/17/2a相同,因此标签为两个极端)
$ g++ -std=c++17 deleteme.cpp && ./a.out
deleteme.cpp: In function ‘int main()’:
deleteme.cpp:6:39: error: the value of ‘array’ is not usable in a constant expression
6 | constexpr auto size2 = array.size(); // does not compile
| ^
deleteme.cpp:5:17: note: ‘array’ was not initialized with a constant expression
5 | auto const& array = arr;
| ^~~~~
但如果我们删除&,它会编译。
另一方面,如果我只是依靠注释,上面写着‘array’ was not initialized with a constant expression,我会假设以下编译
#include <array>
int main() {
constexpr auto arr = std::array<int,3>{{1,2,3}};
constexpr auto size1 = arr.size(); // OK
constexpr auto& array = arr;
constexpr auto size2 = array.size(); // does not compile
}
但它没有并且编译器说(消息错误与-std=11/14/17/2a相同)
$ g++ -std=c++17 deleteme.cpp && ./a.out
deleteme.cpp: In function ‘int main()’:
deleteme.cpp:5:29: error: ‘arr’ is not a constant expression
5 | constexpr auto& array = arr;
| ^~~
这基本上意味着arr 不是“常量表达式”,即使它是constexpr,这在我看来至少是一个非常糟糕的措辞。
【问题讨论】:
-
您能否决定要引用哪个标准文档?我编辑了标签以匹配您报告的测试,但现在您使用 C++11 添加了一个测试
-
@StoryTeller-UnslanderMonica 描述的行为在所有标准版本 C++11-C++20 中都是相同的。
-
@ecatmur - 是但不是。在每个已发布的标准中,措辞都越来越精确。对行为的描述几乎不一样。
标签: c++ c++11 c++17 language-lawyer constexpr