2013-10-02 71 views
1

我想在C++/CLI中編寫一個泛型函數,它將創建一個泛型列表。列表的類型參數與通用函數的類型相同。用C++/CLI從泛型函數返回泛型列表

C#我只是這樣做:

using System.Collections.Generic; 

class MyClass 
{ 
    static List<T> CreateList<T>() 
    { 
     return new List<T>(); 
    } 
} 

C++/CLI我嘗試做相同,即

using namespace System::Collections::Generic; 

generic <typename T> 
List<T>^ MyClass::CreateList (void) 
{ 
    return gcnew List<T>(); 
} 

,但我得到的是一個編譯錯誤: 錯誤C2371:'list':重新定義;不同的基本類型

我在做什麼錯?

注意:實際的功能會比創建一個列表做更多的事情,但這是我卡住的地方。

編輯: 嗨,大家好,感謝您的答覆

顯然,我得到的錯誤是誤導。我創建了一個僅包含main())MyClass的新解決方案,並得到了一個不同的錯誤。然後,我嘗試了Hans Passant的代碼,並且神奇地發揮了作用。再次看看我能看到的唯一區別是,我完全符合列表類型 即System :: Collections :: Generic :: List而不是List(但爲了清楚起見,我在前面的文章中省略了這一點)。事實證明,編譯器出於某種原因不喜歡這樣。即

using namespace System::Collections::Generic; 

generic <typename T> 
System::Collections::Generic::List<T>^ MyClass::CreateList() 
{ 
    //return gcnew System::Collections::Generic::List<T>; // this gives compile error 
    return gcnew List<T>; // this is all right 
} 

我不知道這是否是一個錯誤或有一個理由吧...再次 感謝您的幫助!

+0

哪裏編譯錯誤*正是*什麼是類本身的函數聲明? – Medinoc

+0

有類似的錯誤。刪除顯式名稱空間也適用於我。編譯器錯誤我猜。 – richb

回答

2

很難猜出錯誤信息的來源。 「list」中的L不是大寫,確保你不會遇到std :: list模板類的麻煩。確保以前的類聲明之前該方法不會丟失分號。安美居,正確的代碼應該是這樣的:

類聲明:

using namespace System::Collections::Generic; 

ref class MyClass 
{ 
public: 
    generic <typename T> 
    static List<T>^ CreateList(); 
};         // <== note semi-colon here. 

方法定義:

generic <typename T> 
List<T>^ MyClass::CreateList() 
{ 
    return gcnew List<T>; 
}