user3764855
user3764855

Reputation: 297

How to use anonymous functions?

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.

Upvotes: 3

Views: 468

Answers (1)

Daniel
Daniel

Reputation: 1051

I think that you should actually want

I := Compare(A[1], A[2]);

or

I := Compare(A[First], A[Last]);

instead of

I := Compare(1, 2);

As TLama already mentioned: Compare expects two parameters of type T. A is an array of T, so you can supply its members. 1 and 2 however are integers.

The fact that you later on say that you want T to be an integer is not relevant at this point: If you can say at this point that your code ALWAYS will use integer as T, then you shouldn't use a generic

Upvotes: 2

Related Questions