How can I properly use Anonymous Functions? I am trying use a generic compare function but I get the following error in the example bellow. Can someone explain why does this happen?
program Project11;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
type
TSort<T> = record
private
type
TCompare = reference to function(const L, R: T): Integer;
public
class procedure Sort(var A: Array of T; const First, Last: Integer; const Compare: TCompare); static;
end;
{ TSort<T> }
class procedure TSort<T>.Sort(var A: array of T; const First, Last: Integer; const Compare: TCompare);
var
I: Integer;
begin
I := Compare(1, 2); // [dcc32 Error] Project11.dpr(30): E2010 Incompatible types: 'T' and 'Integer'
end;
var
A: Array of Integer;
begin
TSort<Integer>.Sort(A, 1, 2,
function(const L, R: Integer): Integer
begin
// Do something with L & R
end);
end.
TArray.Sort<T>inGenerics.Collectionsimplements this already. And also, FWIW, your compare function is no good. Imagine what happens whenLishigh(Integer)andRislow(Integer).System.Generics.CollectionsandSystem.Generics.Defaults.TArray.Sort<Integer>(A). If you want to supply a compare function you useTArray.Sort<Integer>(A, TComparer<Integer>.Construct(Comparison))whereComparisonis your anonymous method.