[fpc-pascal] How to assign overloaded event handler?

Thomas Kurz fpc.2021 at t-net.ruhr
Wed Sep 14 16:12:02 CEST 2022


I don't know whether this is actually a bug or not but I cannot find a hint in the documentation.

It seems that methods assigned to an event handler are not allowed to be overloaded. Or, to be more precise, FPC always uses the first declaration regardless whether it fits or not.

Example:


program Project1;

uses Classes;

type TTest = class(TObject)
  procedure SomeEvent (Sender: NativeInt); overload;
  procedure SomeEvent (Sender: TObject); overload;
end;

procedure TTest.SomeEvent (Sender: TObject);
begin
end;

procedure TTest.SomeEvent (Sender: NativeInt);
begin
end;

var
  x: TTest;
  y: TStringList;

begin
  x := TTest.Create;
  y := TStringList.Create;
  y.OnChange := @x.SomeEvent;
end.



This doesn't work:

project1.lpr(25,17) Error: Incompatible types: got "<procedure variable type of procedure(NativeInt) of object;Register>" expected "<procedure variable type of procedure(TObject) of object;Register>"

However, when switching both SomeEvent declarations so that the "TObject" variant appears first, it does work.

Imho, it should considered a bug because the compiler should be able to detect that there is a matching overloaded method and assign that one.

In my simple example, the solution is, of course, to swap declarations. But I'm assigning event handler to a generic class and need event handlers with different types. And it would be helpful if they had the same name when serving the same purpose.

Is there a possibility to tell FPC to use a particular method in the assignment? Something like "OnChange:=@(TNotifyEvent(SomeEvent))"?

Kind regards,
Thomas



More information about the fpc-pascal mailing list