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

det*_*zed 5 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;
Run Code Online (Sandbox Code Playgroud)

此代码在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 };
          ^
Run Code Online (Sandbox Code Playgroud)

据我所知,int有和没有花括号的初始化应该是等价的.Clang i正确初始化42,只是不认为它是编译时常量.

此代码在C++ 11模式下编译良好.

有没有理由j被视为编译时常量而i不是?或者它只是Clang中的一个错误?

更新:我在LLVM错误跟踪器中打开了此问题的故障.

Mik*_*our 5

是的,根据C++ 98 8.5/13,两个声明都是等效的:

如果T是标量类型,则表示声明

T x = { a };
Run Code Online (Sandbox Code Playgroud)

相当于

T x = a;
Run Code Online (Sandbox Code Playgroud)

因此两个变量都是常量,并从常量表达式初始化,因此(据我所见)应该都可以用作常量表达式.


Rax*_*van 2

编译器错误表明"template argument of type 'int' is not an integral constant expression"对于int const i = { 42 };

根据98 标准,模板参数应该属于这一类:

14.3.2 / 1

非类型、非模板模板参数的模板参数应为以下之一:

  • 整型或枚举类型的整型常量表达式;或者

...

整型常量表达式的定义int const i属于这一类:

5.19 常量表达式

整型常量表达式只能涉及文字 (2.13)、枚举数、const 变量或静态数据成员

以及初始化i(如 Mike Seymour 帖子):

8.5 初始化器/13

如果 T 是标量类型,则形式的声明

T x = { a };

相当于

Tx=a;

现在根据这篇文章const int,和 的声明int const应该是相同的(在标准中找不到这个具体内容),制作i一个const 变量i因此,无论初始化方法如何,的任何用法都应该是整型常量表达式。clang 似乎有一个错误。检查网络我找不到错误报告,只有两个或多或少相似:

http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=666539

http://lists.cs.uiuc.edu/pipermail/llvmbugs/2011-March/017353.html