Lazarus

Free Pascal => General => Topic started by: CCRDude on December 27, 2022, 03:09:41 pm

Title: Method parameters for methods in generics?
Post by: CCRDude on December 27, 2022, 03:09:41 pm
Question: how do I pass (unknown) parameters to a generic record?

Background: I want a simple way to convert 1:1 event properties to 1:n event properties. Instead of adding Add... and Remove... handlers to handle multiple event methods, I'm trying a generic record.

The following record with example allows to either pass a single method, or add multiple ones to the same property.

The point where I'm looking to simplify things is within calling the events. I can add a trigger method (TSomeClass.Test as below) that iterates through events. I would love to have the iterator within the generic record, like
Code: [Select]
TEventMultiplexer.Trigger(<TEventParameters>) begin for t in Events do t(<TEventParameters>) end...

Is there any way to do that with generics?

Code: Pascal  [Select][+][-]
  1.    TEventMultiplexer<TEvent> = record
  2.       Events: array of TEvent;
  3.       class operator implicit(AnEvent: TEvent): TEventMultiplexer<TEvent>;
  4.       class operator explicit(AMultiplexer: TEventMultiplexer<TEvent>): TEvent;
  5.       class operator add(AMultiplexer: TEventMultiplexer<TEvent>; AnEvent: TEvent): TEventMultiplexer<TEvent>;
  6.       class operator subtract(AMultiplexer: TEventMultiplexer<TEvent>; AnEvent: TEvent): TEventMultiplexer<TEvent>;
  7.    end;                      
  8.  
  9.    TSomeClass = class
  10.    private
  11.       FOnSome: TEventMultiplexer<TOnSomeEvent>;
  12.    public
  13.       procedure Test(AIndex: integer; AText: string);
  14.       property OnSome: TEventMultiplexer<TOnSomeEvent> read FOnSome write FOnSome;
  15.    end;
  16.  
  17. ...
  18.  
  19.    FTestClass.OnSome := Test1;
  20.    FTestClass.OnSome := FTestClass.OnSome + Test2;
  21.  
  22. ...
  23.  
  24. procedure TSomeClass.Test(AIndex: integer; AText: string);
  25. var
  26.    t: TOnSomeEvent;
  27. begin
  28.    for t in FOnSome.Events do begin
  29.       t(AIndex, AText);
  30.    end;
  31. end;    
  32.  
  33.  
Title: Re: Method parameters for methods in generics?
Post by: PascalDragon on December 28, 2022, 02:29:49 pm
The point where I'm looking to simplify things is within calling the events. I can add a trigger method (TSomeClass.Test as below) that iterates through events. I would love to have the iterator within the generic record, like
Code: [Select]
TEventMultiplexer.Trigger(<TEventParameters>) begin for t in Events do t(<TEventParameters>) end...

Is there any way to do that with generics?

I've looked at multicast events in Object Pascal multiple times already and in only code that is simply not possible. What you might be able to do is to use the Rtti unit with TRttiInvokableType.CreateImplementation and TRttiInvokableType.Invoke to create a backbone implementation for it.
TinyPortal © 2005-2018