我偶然发现了我不理解的代码。这是它的简化版本:
template <int> struct A {};
int const i = { 42 };
typedef A<i> Ai;
int const j = 42;
typedef A<j> Aj;
此代码可在 C++98 模式下使用 GCC 进行编译,但不能在 Clang 中进行编译。 Clang 产生以下错误:
$ clang -Wall -Wextra -std=c++98 -c test.cpp
test.cpp:4:11: error: non-type template argument of type 'int' is not an integral constant expression
typedef A<i> Ai;
^
test.cpp:4:11: note: initializer of 'i' is not a constant expression
test.cpp:3:11: note: declared here
int const i = { 42 };
^
据我所知,使用和不使用花括号的 int
初始化应该是等价的。 Clang 将 i
正确初始化为 42
,只是不认为它是编译时间常量。
此代码在 C++11 模式下编译良好。
j
被视为编译时间常量而 i
不是的原因吗?或者它只是 Clang 中的一个错误?
更新:我打开了一个ticket在 LLVM 错误跟踪器中解决这个问题。
最佳答案
是的,根据 C++98 8.5/13,这两个声明是等价的:
If
T
is a scalar type, then a declaration of the form
T x = { a };
is equivalent to
T x = a;
所以这两个变量都是常量,并且从常量表达式初始化,所以(据我所知)应该都可以用作常量表达式。
关于C++98 花括号 const 标量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20662945/