[fpc-pascal] For..in enumerator for generic records?

Sven Barth pascaldragon at googlemail.com
Tue Dec 6 20:51:32 CET 2016


On 02.12.2016 08:22, Ryan Joseph wrote:
> Yes but the problem is doing this with generics. :) That’s where I got stuck and I don’t think it’s possible.

Ah, yes, right, sorry. Attached is a corrected version :)

Regards,
Sven

-------------- next part --------------
program trecenum;

{$mode objfpc}
{$modeswitch advancedrecords}

type
  generic TRec<T> = record
  public type
    TArrayType = array of T;

    TEnumerator = object
    private
      fArr: TArrayType;
      fIndex: Integer;
      function GetCurrent: T;
    public
      constructor Create(aArr: TArrayType);
      function MoveNext: Boolean;
      property Current: T read GetCurrent;
    end;

  public
    arr: TArrayType;

    function GetEnumerator: TEnumerator;
  end;


constructor TRec.TEnumerator.Create(aArr: TArrayType);
begin
  fArr := aArr;
  fIndex := -1;
end;

function TRec.TEnumerator.GetCurrent: T;
begin
  Result := fArr[fIndex];
end;

function TRec.TEnumerator.MoveNext: Boolean;
begin
  Inc(fIndex);
  Result := fIndex < Length(fArr);
end;

function TRec.GetEnumerator: TRec.TEnumerator;
begin
  Result.Create(Self.arr);
end;

type
  TRecLongInt = specialize TRec<LongInt>;
  TRecString = specialize TRec<String>;

var
  rl: TRecLongInt;
  rs: TRecString;
  i: LongInt;
  s: String;
begin
  rl.arr := TRecLongInt.TArrayType.Create(42, 53, 96, 29);
  rs.arr := TRecString.TArrayType.Create('Alpha', 'Beta', 'Gamma', 'Delta');

  for i in rl do
    Writeln(i);

  for s in rs do
    Writeln(s);
end.


More information about the fpc-pascal mailing list