Car*_*cel 0 c++ templates constexpr
以下按预期工作:
#include <array>
constexpr std::array<int, 3> values = {1, 2, 3};
template <int i> struct A { static constexpr int val = values[i]; };
int main() { A<1> a; }
Run Code Online (Sandbox Code Playgroud)
但是,如果我们使用values.size()模板参数,我会从MSVC编译器中收到编译器错误:
int main() { A<values.size()> a; }
Run Code Online (Sandbox Code Playgroud)
错误是表达式没有评估为常量.GCC编译没有错误.
MSVC是对的.在任何constexpr上下文中都不能有未定义的行为.否则这不是一个常数表达式.
这条线:
int main() { A<values.size()> a; }
Run Code Online (Sandbox Code Playgroud)
基本上是:
constexpr auto i = values[values.size()];
Run Code Online (Sandbox Code Playgroud)
哪个是出界的.事实上,MSVC正确诊断错误:
Run Code Online (Sandbox Code Playgroud)example.cpp <source>(3): error C2131: expression did not evaluate to a constant C:/msvc/v19_16/include\array(187): note: failure was caused by out of range index 3; allowed range is 0 <= index < 3 <source>(4): note: see reference to class template instantiation 'A<3>' being compiled <source>(2): note: see reference to class template instantiation 'std::array<int,3>' being compiled Compiler returned: 2
另一方面,GCC和MSVC都接受此代码:
int main() { A<values.size() - 1> a; }
Run Code Online (Sandbox Code Playgroud)