gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:04:12 28 4
gpt4 key购买 nike

我正在用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com