First off, TList<T>
is a Delphi TObject
-derived class, so it must be created dynamically via new
in C++, eg:
TList__1<T> *MyList = new TList__1<T>;
...
delete MyList;
Where T
can be _di_IInterface
, TObject*
(note the *
), etc.
Now, that being said...
How can I create a list of interface instances in C++Builder?
In short, you can't do that with TList<T>
in pure C++ code by itself. This is documented behavior:
How to Handle Delphi Generics in C++
Delphi generics are exposed to C++ as templates. However, it is important to realize that the instantiations occur on the Delphi side, not in C++. Therefore, you can only use these template for types that were explicitly instantiated in Delphi code.
...
If C++ code attempts to use a Delphi generic for types that were not instantiated in Delphi, you'll get errors at link time.
There are no default instantiations of TList<IInterface>
in the native RTL or VCL/FMX frameworks. So you would have to add your own Delphi code to your C++Builder project to create such instantiation, eg:
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
Otherwise, you can use TInterfaceList
instead:
#include <System.Classes.hpp>
...
TInterfaceList *IntfList = new TInterfaceList;
...
delete IntfList;
Or, if you don't really need to pass an interface list across the C++/Delphi boundary, then consider using a pure-C++ container like std::vector
instead, eg:
#include <vector>
...
std::vector<_di_IInterface> IntfList;
As for TList<TObject>
, it actually does exist in the native Delphi RTL, but it is not working for you simply because you are not using it correctly. It needs to look more like this instead:
TList__1<TObject*> *ObjList = new TList__1<TObject*>;
...
delete ObjList;
Otherwise, you can use TObjectList
instead, eg:
#include <System.Contnrs.hpp>
...
TObjectList *ObjList = new TObjectList;
...
delete ObjList;
Or, just use std::vector<TObject*>
instead.