generics - C++/CLI 泛型,在 array<> 和其他集合中使用 T

标签 generics collections c++-cli

我正在用 C++/CLI (VS2008) 编写一个泛型类来存储和管理不同类型的记录,我需要集合来保存它们,然后再将它们传输到数据库/磁盘/等。我在想这样的事情:

ref class Record
{
    // ...
};

generic<typename T>
where T : Record, gcnew()
public ref class Factory
{
public:
    // ....functions....
protected:
    array<T^> ^    StoredData;
};

当然失败并出现错误 C3229(不允许对泛型类型参数进行间接寻址)。如果我删除“^”,则错误为 C3149(如果没有顶级“^”,则无法在此处使用此类型)。这在 VB.Net 中很容易完成(事实上,我正在迁移现有的 VB.Net 类!),但在 C++ 中我似乎已经走进了死胡同。这在 C++/CLI 中实际上不可能吗?

提前致谢。

最佳答案

您需要做的是:

public ref class Record
{
};

generic<typename T>
where T : Record, gcnew()
public ref class Factory
{
public:
    // ....functions....
protected:
    array<T> ^    StoredData;
};

然后您可以像这样实例化该集合:

Factory<Record^>^ records = gcnew Factory<Record^>();

这是 MSDN 关于 C++ 中的泛型的说法:

Both value types (either built-in types such as int or double, or user-defined value types) and reference types may be used as a generic type argument. The syntax within the generic definition is the same regardless. Syntactically, the unknown type is treated as if it were a reference type. However, the runtime is able to determine that if the type actually used is a value type and substitute the appropriate generated code for direct access to members. Value types used as generic type arguments are not boxed and so do not suffer the performance penalty associated with boxing. The syntax used within the body of the generic should be T^ and '->' instead of '.'. Any use of gcnew for the type parameter will be appropriately interpreted by the runtime as the simple creation of a value type if the type argument is a value type.

因此,我认为这意味着任何泛型类型参数都被视为指向托管类(即 T^)的指针。事实上,您不能使用如下方式实例化泛型类:

Factory<Record>^ records = gcnew Factory<Record>();

编译器将抛出此错误(即使您删除 where T : Record, gcnew()):

error C3225: generic type argument for 'T' cannot be 'Record', it must be a value type or a handle to a reference type

关于generics - C++/CLI 泛型,在 array<> 和其他集合中使用 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1856944/

相关文章:

generics - 在 Rust 中编写一个将可迭代容器作为参数的通用函数

java集合: Filter using mapped values and then return to initial values

java - 如何使用另一个列表中的对象的属性创建一个新列表

c++ - "Unresolved Typeref-Token"与 SDL_net 和 .NET

visual-studio - Monitor.Exit() 上的 SynchronizationLockException?

双倍的正则表达式

c# - 将派生类的列表<>转换为基类的列表<>

c# - 如何禁用泛型复杂类型字段的延迟加载?

c# - 在 C# 7 本地方法中重新引入新的泛型参数是一个好习惯吗?

java - 如何获得两个列表的笛卡尔积?