前向声明的类型和"non-class type as already been declared as a class type"

Forward-declared type and "non-class type as already been declared as a class type"

本文关键字:type as already declared class been non-class 声明 类型      更新时间:2023-10-16

我对以下代码有问题:

  template <typename T>
  void foo(struct bar & b);
  struct bar {};
  int main(){}

它在 GCC 上成功编译,但在 MSVC (2008) 上失败,出现以下错误:

C2990: 'bar' : non-class type as already been declared as a class type

是代码错误还是 MSVC 中的错误?

如果我在模板定义之前添加struct bar;,它可以工作。

我们有赢家:

https://connect.microsoft.com/VisualStudio/feedback/details/668430/forward-declared-type-and-non-class-type-as-already-been-declared-as-a-class-type

感谢您报告此问题。 这确实是一个案例 VC++ 中的不合规行为。 但是,一个简单的解决方法是 对声明重新排序,以便 声明"结构栏"已知何时 模板声明是 遇到。由于严重性低 对于这个错误和我们的优先事项,我们 很遗憾我们无法修复错误 编译器的下一个版本,但是 我们将在未来考虑它 释放。

问候

坦维尔·加尼 视觉C++团队

在大多数情况下,C(或C++编译器)严格从上到下地在源代码上工作。 所以在尝试引用struct bar之前,你需要一个前向声明,否则编译器将不知道它的存在。

无论如何,我在Microsoft Connect中发布了一个错误:https://connect.microsoft.com/VisualStudio/feedback/details/668430/forward-declared-type-and-non-class-type-as-already-been-declared-as-a-class-type

您很可能struct bar {};此代码块上方的某个位置(可能在头文件中)。 请参阅 http://msdn.microsoft.com/en-us/library/zfcw8kk9.aspx

编辑:也来自上面的链接:

C2990 也可能由于断裂而发生 在 的可视C++编译器中更改 视觉C++2005;现在的编译器 要求多个声明 对于相同的类型,与 尊重模板规范。

由于foo是模板化的,并且barfoo参数列表中被"向前声明",因此如果您将struct bar {};移动到foo上方会发生什么?

这看起来像是有效的代码。无论MSVC在做什么,从我所看到的情况来看,它似乎是一些奇怪的不合规行为。

相关文章: