c++ - 模板函数中使用的类的前向声明不是由 clang++ 编译的

标签 c++ templates g++ forward-declaration clang++

有这个代码:

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/

相关文章:

c++ - 无效使用不完整类型 'class...'

javascript - 在 Ember.js 中集成测试路由模板

c++ - 为什么 g++ 会警告返回对临时对象的引用

c++ - 类范围内的类模板特化?

c++ - 如何为一段代码启用 -fpermissive

c++ - 定义一种新型优化

c++ - Bitblt,createdibsection,图像损坏

c++ - 将一个 STL 容器的内容复制到另一个 STL 容器

c++ - 内部编译器错误(CL版本:14.27.29110)

c++ - 隐藏成员模板的模板参数