The problem is best explained when you look at some sample code (I've deleted all unnecessary code):
program XE8GenericArrayTest;
{$APPTYPE CONSOLE}
type
TArrayUtilCls<T: class> = class
public
class procedure AddArray<U: T>(var Arr_: TArray<T>; ArrayToAdd: TArray<U>);
class procedure MergeArrays(var Arr_: TArray<T>; ArrayToAdd: TArray<T>);
end;
TBaseCls = class
end;
TChild = class(TBaseCls)
end;
{ TArrayUtilCls<T> }
class procedure TArrayUtilCls<T>.AddArray<U>(var Arr_: TArray<T>;
ArrayToAdd: TArray<U>);
begin
// ... some logic to merge the arrays
end;
class procedure TArrayUtilCls<T>.MergeArrays(var Arr_: TArray<T>;
ArrayToAdd: TArray<T>);
begin
// THE FOLLOWING CODE LINE DOES NOT COMPILE
// E2515 Type parameter 'U' is not compatible with type 'T'
AddArray<T>(Arr_, ArrayToAdd);
end;
var
ArrBase: TArray<TBaseCls>;
ArrChildren: TArray<TChild>;
begin
// ... allocate memory
TArrayUtilCls<TBaseCls>.AddArray<TChild>(ArrBase, ArrChildren);
end.
The class TArrayUtilCls
contains a method to add an array of subtypes to an array of base types AddArray
- this works fine.
Now I also want to add a method that does the same for 2 arrays which are of the same type: MergeArrays
.
I think it should simply work to call the AddArray<T>
method, since U
must extend from T
anyway: But Delphi gives me a compile error (see comment in the source-code).