此类代码可以通过 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/