c++ - 在 clang 中实例化后的静态成员初始化

标签 c++ gcc clang

此类代码可以通过 GCC 编译,但 clang 3.5 失败。

#include <iostream>
using namespace std;

template<typename T>
class C{
public:
  const static int x;
};

int main(){
  cout << C<int>::x;
}

template<>
const int C<int>::x = 4;

Clang 返回消息:

hello.cpp:15:19: error: explicit specialization of 'x' after instantiation
const int C<int>::x = 4;
                  ^
hello.cpp:11:19: note: implicit instantiation first required here
  cout << C<int>::x;
                  ^

是代码中的错误,还是 clang 编译器中的错误?它是否符合标准,或者 GCC 更宽松并编译非标准代码?

最佳答案

程序有误。 C++11 14.7.3/6 说:

If a template [...] is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place

您的代码在 main 中使用它,在那里导致隐式实例化,然后稍后声明特化,如错误消息所述。

关于c++ - 在 clang 中实例化后的静态成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200678/

相关文章:

c++ - gcc 编译 C++ 代码 : undefined reference to `operator new[](unsigned long long)'

c++ - 如何在编译时测试 libstdc++ 的版本,而不是 GCC?

c++ - noexcept 运算符和 enable_if_t : do they work together?

c++ - 为什么此代码会出现错误 "template specialization requires ' template< >'"?

c++ - 键盘有一些问题

c++ - 修改后的Fibonacci C++产生较大的负数

c++ - Qt 布局的父级?

c++ - 覆盖一个 char * 指针

不能用 GCC 包含文件

c - 使用 GCC 中的 4 位 PowerPC CR0 寄存器