2

我正在尝试在 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 的代码,它神奇地起作用了。再看看我能看到的唯一区别,是我完全限定了 List 类型,即 System::Collections::Generic::List 而不是 List(但是为了清楚起见,我在之前的帖子中省略了它)。事实证明,编译器出于某种原因不喜欢那样。IE

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
}

我不知道这是一个错误还是有原因......再次感谢您的帮助!

4

1 回答 1

3

很难猜测该错误消息的来源。“list”中的 L 没有大写,请确保您没有遇到 std::list 模板类的问题。确保方法之前的前一个类声明没有缺少分号。Anyhoo,正确的代码如下所示:

类声明:

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>;
}
于 2013-10-02T12:27:29.280 回答