C++98 花括号 const 标量初始化

标签 c++ gcc clang c++98

我偶然发现了我不理解的代码。这是它的简化版本:

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/

相关文章:

c++方法可见性继承通过g++中的不同命名空间

c++ - Qt:QSS 和 drawComplexControl()

gcc - red hat devtoolset-3 中的 g++ 找不到 -lelf

c++ - g++ 不允许使用标识符中的😃(和其他 Unicode 字符)

c++ - #include 会影响程序大小吗?

c++ - 从 QT 中的 C++ 代码访问 QML 元素

c++ - _T( ) 宏更改为 UNICODE 字符数据

c++ - 如何可靠地让析构函数覆盖缓冲区而不在 C++ 中对其进行优化

c++ - CMake:如何选择不同的外壳

c++ - C++11 std::map 程序无法在 clang 3.4 中编译