我发现了一段我不理解的代码。这是一个简化版本:
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中的一个bug?更新:我在LLVM bug跟踪器中开了一个ticket来处理这个问题。