有这个代码:
class A;
template <class T>
void fun() {
A a;
}
class A {
public:
A() { }
};
int main() {
fun<int>();
return 0;
}
g++ 4.5 和 g++ 4.7 编译它没有错误。但是 clang++ 3.2 (trunk) 给出了这个错误:
main.cpp:5:6: error: variable has incomplete type 'A'
A a;
^
main.cpp:1:7: note: forward declaration of 'A'
class A;
^
那么根据 C++ 标准,哪个编译器是正确的?
最佳答案
Which compiler is right then according to C++ standard?
两者都是正确的。这是一个格式错误的程序。强调我的:
N3290 14.6¶9
If a type used in a non-dependent name is incomplete at the point at which a template is defined but is complete at the point at which an instantiation is done, and if the completeness of that type affects whether or not the program is well-formed or affects the semantics of the program, the program is ill-formed; no diagnostic is required.
clang++ 和其他编译器确实在这里发出诊断是一个不错的附加功能,但诊断不是强制性的。 “程序格式错误;不需要诊断”这一条款让编译器开发人员可以在这种情况下自由地做任何事情,并且仍然符合要求。
关于c++ - 模板函数中使用的类的前向声明不是由 clang++ 编译的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10993720/