Question

Given a generic type

TMyClass <T> = class
  ...
end;

is there a way to put multiple instances (instantiated with different types) together like

FList : TList <TMyClass>;
FList.Add (TMyClass <Integer>.Create);
FList.Add (TMyClass <String>.Create);

or

FArray : array [0..1] of TMyClass;
FArray [0] := TMyClass <Integer>.Create;
FArray [1] := TMyClass <String>.Create;

I know that this code does not compile. But is it possible to achieve something like that?

Was it helpful?

Solution

You can do that if you create FList with the ancestor of TMyClass.

Generics are not inheritance so TMyClass is not the ancestor of TMyClass.

TMyAbstractClass = class
TMyClass <T> = class (TMyAbstractClass)
  ...
end;

FList : TList <TMyAbstractClass>;
FList.Add (TMyClass <Integer>.Create);
FList.Add (TMyClass <String>.Create);

FArray : array [0..1] of TMyAbstractClass;
FArray [0] := TMyClass <Integer>.Create;
FArray [1] := TMyClass <String>.Create;

OTHER TIPS

One option is to have a non-generic base class for TMyClass containing all the bits which don't refer to T in. You then create a TList<TMyNonGenericBaseClass> and add the instances to that. Of course you then don't know what the full concrete type is when you get them out again, but that may not be an issue for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top