[fpc-pascal] How to avoid Copy

Amir at Aavani.net Amir at Aavani.net
Wed Jan 3 07:53:30 CET 2024


Yeap! That is actually what I posted here (Feature Request) 
<https://gitlab.com/freepascal.org/fpc/source/-/issues/40578>.

>  You simply need to inherit from the list class so that you can make 
> the function public. And with a little trick you can also use it 
> inside a for-in-loop:
>
> === code begin ===
>
> program tlistitr;
>
> {$mode objfpc}{$H+}
> {$modeswitch advancedrecords}
>
> uses
>   Generics.Collections;
>
> type
>   TRec = record
>     a, b, c: Int64;
>     constructor Create(aArg1, aArg2, aArg3: Int64);
>   end;
>
>   { this way the GetPtrEnumerator function is available; you could 
> also use a class helper }
>   TMyList = class(specialize TList<TRec>)
>   public
>     function GetPtrEnumerator: specialize TEnumerator<PT>;
>   end;
>
> constructor TRec.Create(aArg1, aArg2, aArg3: Int64);
> begin
>   a := aArg1;
>   b := aArg2;
>   c := aArg3;
> end;
>
> function TMyList.GetPtrEnumerator: specialize TEnumerator<PT>;
> begin
>   Result := inherited GetPtrEnumerator();
> end;
>
> { with this you can simply do "for PtrTypeVar in List.GetPtrEnumerator 
> do",
>   though this *might* not work in mode Delphi... }
> operator Enumerator(aEnum: specialize TEnumerator<TMyList.PT>): 
> specialize TEnumerator<TMyList.PT>;
> begin
>   Result := aEnum;
> end;
>
> var
>   l: TMyList;
>   r: TRec;
>   p: TMyList.PT;
> begin
>   l := TMyList.Create;
>   l.Add(TRec.Create(1, 2, 3));
>   l.Add(TRec.Create(9, 8, 7));
>   for p in l.GetPtrEnumerator do begin
>     Writeln(p^.a, ' ', p^.b, ' ', p^.c);
>   end;
> end.
>
> === code end ===
>
> Regards,
> Sven
>
> _______________________________________________
> fpc-pascal maillist  -fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20240102/847a0aa7/attachment.htm>


More information about the fpc-pascal mailing list