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

Anthony Walter sysrpl at gmail.com
Sun Nov 22 00:04:03 CET 2015


Sven, first off, congratulations and we thank you for so much good work. in
the future do you see a time when type inference could be used?

S := Add('hello ', 'world');
I := Add(1, 2);

For everyone else, I can also imagine:

function Max<T>(const A, B: T): T; begin if A > B then Result := A else
Result := B; end;
function Compare<T>(const A, B: T): Integer; begin if A > B then Exit(1);
if B > A then Exit(-1); Result := 0; end;

Possibly allowing for ...

function IListHelper<T>.Sort; begin QuickSort(Compare<T>); end;

Which then brings to mind, will it be possible to get use references to
generic routines?

type
  TTransform<T> = function<T>(const A, B: T): T;

var
  Transform: TTransform<T>;
begin
  Transform := Add<String>;
  WriteLn(Transform('hello', 'world'));
  Transform := Min<String>;
  WriteLn(Transform('hello', 'world'));
  Transform := Max<String>;
  WriteLn(Transform('hello', 'world'));
end;

output:

helloworld
hello
world

Leading to ...

function Print<T>(const A, B: T; Transform: TTransform<T>);
begin
  WriteLn(Transform(A, B));
end;

begin
  Print('hello', 'world', Add); // type inference
  Print('hello', 'world', Min);
  Print('hello', 'world', Max);
end;

output:

helloworld
hello
world
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20151121/09161d8e/attachment.html>


More information about the fpc-devel mailing list