I'm having some trouble with generics and constructors.
I would like to have a Generic class that can handle (and create) multiple objects of the same class. Moreover, I have some code that I would like to use whatever the specific class actually is.
I thought Generics are a good solution to this, but I'm not quite sure.
type
TMultiBlock<T: IBlock, constructor> = class(TObject)
blocks: array of array of T;
constructor Create(const owner: someClass, const n: integer);
end;
constructor TMultiBlock<T>.Create(const owner: someClass, const n: integer);
var
i: integer;
begin
for i := 0 to n-1 do
T.Create();
end;
The solution above works, but the Create()
that is called is not the one of the class T
that I give to the Generic.
I know that I can do the Create
outside the TMultiBlock
class, since I know class T
there, as show below:
TM := TMultiBlock<TFinestra>.Create();
for i := 0 to n do
begin
TM.blocks[i] := TFinestra.Create();
end;
Here the class TFinestre
is one of the class that I want to use in the Generic. But the thing is that I want to do some common operations on the T
element, and these operation will be common to whatever the T
type is, so I would like to do them on the TMultiBlock
.
IBlock
is an interface implemented by each class of type T
.