2011-05-13 180 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在做什麼,似乎都是一些奇怪的不符合規定的行爲,從我看到的情況來看。