[fpc-pascal] Feature announcement: Generic functions, procedures and methods
Anthony Walter
sysrpl at gmail.com
Sun Nov 22 21:29:25 CET 2015
Here are a few tests ...
Test 1 works:
function Swap<T>(var A, B: T): T;
var
C: T;
begin
C := A;
A := B;
B := C;
end;
Example 1 usage:
Swap<Integer>(I, J); // J now holds I value, I value holds J
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);
I could not use this as a method, for example:
function TForm1.Find<T>: T;
Question:
Will it be possible to use type constraints?
function TForm1.Find<T: TComponent>: T;
or
function Find<T: TComponent>: T;
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;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20151122/977e4a15/attachment.html>
More information about the fpc-pascal
mailing list