In C duck typing there is the concept of a callable, e.g. a symbol that can be called like a function. I'd like to emulate this with Delphi generics.
I have a problem where I need a procedure that can accept either a normal procedure, a class method or a lambda as argument. Right now I have 3 almost identical overloaded implementations. Is there a way to use Delphi generics to avoid this duplication?
CodePudding user response:
You don't need generics for this.
The reference to X
is compatible with X
, X of object
, and reference to X
(where X
is a procedural type such as procedure(X: Integer)
).
For example,
program Project1;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TTestProc = procedure(X: Integer);
TTestMeth = procedure(X: Integer) of object;
TTestRef = reference to procedure(X: Integer);
// Ordinary procedure
procedure TestProc(X: Integer);
begin
end;
// Method
type
TMyClass = class
class procedure TestMeth(X: Integer);
end;
class procedure TMyClass.TestMeth(X: Integer);
begin
end;
begin
var A: TTestRef;
A := TestProc;
A := TMyClass.TestMeth;
A := procedure(X: Integer) begin end;
end.