首先,TList<T> 是 Delphi 的 TObject 派生类,因此它必须在 C++ 中通过 new 动态创建,例如:
TList__1<T> *MyList = new TList__1<T>;
...
delete MyList;
其中T 可以是_di_IInterface、TObject*(注意*)等
现在,话虽这么说......
如何在 C++Builder 中创建接口实例列表?
简而言之,你不能在纯 C++ 代码中单独使用 TList<T> 来做到这一点。这是记录在案的行为:
How to Handle Delphi Generics in C++
Delphi 泛型作为模板暴露给 C++。然而,重要的是要意识到实例化发生在 Delphi 端,而不是在 C++ 中。因此,您只能将这些模板用于在 Delphi 代码中显式实例化的类型。
...
如果 C++ 代码尝试对未在 Delphi 中实例化的类型使用 Delphi 泛型,您将在链接时收到错误。
在原生 RTL 或 VCL/FMX 框架中没有 TList<IInterface> 的默认实例化。因此,您必须将自己的 Delphi 代码添加到您的 C++Builder 项目中才能创建这样的实例化,例如:
MyTListInstantiationUnit.pas
unit MyTListInstantiationUnit;
interface
{$HPPEMIT '#pragma link "MyTListInstantiationUnit"'}
// or in XE5 Update 2 and later:
// {$HPPEMIT LINKUNIT}
implementation
uses
System.Generics.Collections;
initialization
TList<IInterface>.Create.Free;
finalization
end.
MyCppUnit.cpp
#include <System.Generics.Collections.hpp>
#include "MyTListInstantiationUnit.hpp"
...
TList__1<_di_IInterface> *IntfList = new TList__1<_di_IInterface>; // should work now
否则,您可以改用TInterfaceList:
#include <System.Classes.hpp>
...
TInterfaceList *IntfList = new TInterfaceList;
...
delete IntfList;
或者,如果您真的不需要跨 C++/Delphi 边界传递接口列表,则可以考虑使用像 std::vector 这样的纯 C++ 容器,例如:
#include <vector>
...
std::vector<_di_IInterface> IntfList;
至于TList<TObject>,它确实存在于本机Delphi RTL 中,但它不适合你,只是因为你没有正确使用它。它需要看起来更像这样:
TList__1<TObject*> *ObjList = new TList__1<TObject*>;
...
delete ObjList;
否则,您可以使用TObjectList 代替,例如:
#include <System.Contnrs.hpp>
...
TObjectList *ObjList = new TObjectList;
...
delete ObjList;
或者,直接使用std::vector<TObject*>。