[fpc-pascal] Feature announcement: Generic functions, procedures and methods

Sven Barth pascaldragon at googlemail.com
Sun Nov 22 22:59:30 CET 2015


On 22.11.2015 21:29, Anthony Walter wrote:
> Test 2 works but with notes:
>
> function Find<T>: T;
> var
>    I: Integer;
> begin
>    for I := 0 to Form1.ComponentCount - 1 do
> if Form1.Components[I].InheritsFrom(T) then
> Exit(T(Form1.Components[I]));
>    Result := nil;
> end;
>
> Example 2 usage:
>
> Find<TShape>.Brush.Color := clRed;
>
> Notes:
>
> Cannot use 'as' or 'is' operators. I had to use
>
>    if Form1.Components[I].InheritsFrom(T) then
> Exit(T(Form1.Components[I]));
>
> Instead of
>
>    if Form1.Components[I] is T then
> Exit(Form1.Components[I] as T);

Of course, because T is not an object (though one could argue that 
everywhere else regarding generics we are much less picky...). 
Nevertheless since you're in mode Delphi anyway, this wouldn't work in 
Delphi either.

> I could not use this as a method, for example:
>
> function TForm1.Find<T>: T;

Please show the code and the error message, because here it works.

> Question:
>
> Will it be possible to use type constraints?
>
> function TForm1.Find<T: TComponent>: T;
> or
> function Find<T: TComponent>: T;

Already works (and there you can use "as" and "is", though this would 
already work with a "TObject" or - Delphi compatible - "class" 
constraint). [Constraints themselves are already part of 3.0.0]

> Test 3 does not work:
>
> function Compare<T>(constref A, B: T): Integer;
> begin
>    if A > B then
>      Result := 1
> else if B > A then
> Result := -1
>    else
>      Result := 0;
> end;
> procedure Test3;
> var
>    Items: TArrayList<Single>; // See Codebot.System
> begin
>    Randomize;
>    Items.Push(Random * 100);
>    Items.Push(Random * 100);
>    Items.Push(Random * 100);
>    Items.Push(Random * 100);
>    // compile fails below
>    Items.Sort(soDescend, @Compare<Single>); // cannot take address of
> Compare<Single>
> end;

As mentioned in my announcement this is a limitation I have yet to address.

Regards,
Sven



More information about the fpc-pascal mailing list