2011-05-13 134 views
6

我有下面的代码的问题:前置声明型和“非类类型已经被声明为类型”

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

它successfuly上编译GCC,但未能在MSVC(2008)与以下错误:

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

代码是否错误或它在MSVC的错误吗?

它可以在模板定义之前添加struct bar;

+1

也没有用VC++ 2010神,有什么可怕的用于C++开发的IDE已经成为! – 2011-05-13 20:04:15

回答

3

,我们有我们的赢家:

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

Thank you for reporting this issue. This is indeed a case of non-conformant behaviour in VC++. However, a simple workaround is to reorder the declarations so that the declaration "struct bar" is known when the template declaration is encountered. Due to the low severity of this bug and our priorities, we regret that we cannot fix the bug in the next release of the compiler but we will consider it for a future release.

Regards,

Tanveer Gani Visual C++ Team

0

你很可能有struct bar {};在这个代码块的上面(可能在头文件中)。见http://msdn.microsoft.com/en-us/library/zfcw8kk9.aspx

编辑:

C2990 can also occur due to a breaking change in the Visual C++ compiler for Visual C++ 2005; the compiler now requires that multiple declarations for the same type be identical with respect to template specification.

由于foo是模板和bar被“前瞻性声明”,在foo参数列表,如果你移动struct bar {};上述foo会发生什么:从上面的链接还?

+0

不,这是完整的,最小的代码。 – 2011-05-13 17:50:22

+0

@你好在你的评论编辑基地。 – 2011-05-13 17:56:26

+0

回复您的编辑:是的,它会工作。此外,_It工程,如果我添加结构栏;之前模板definition._像我写在我的问题。 – 2011-05-13 18:48:26

3

在大多数情况下,C(或C++编译器)在您的源代码上严格按照从上到下的顺序执行。因此,在您尝试引用struct bar之前,您需要一个forward declaration,否则编译器将不知道它存在。

+0

您可以进行内联转发声明。像'void foo(struct bar & b);'。** struct **关键字在这里是前向声明。 – 2011-05-13 17:55:13

+0

@你好:真的吗?我不是说你错了,只是我以前从未见过。提供一个引用? – 2011-05-13 18:08:32

+0

@Oli:尝试它没有模板,它会编译。:) – Xeo 2011-05-13 18:13:10

0

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