Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declarations for record types (or arrays)

I want to do this in XE5:

type
  TMyRec = record
    // fields
    class function GetList: TMyRecArr; static;
  end;

  TMyRecArr = array of TMyRec;

I've already seen "Forward declarations for record types" and "how to do a typed forward declaration?", but they seem irrelevant since my problem is not passing the record as a parameter.

like image 642
saastn Avatar asked Sep 29 '15 16:09

saastn


2 Answers

You cannot use a forward declaration to declare a record type or an array type. But not to fear. You can use a generic dynamic array, TArray<T>.

type
  TMyRec = record
    class function GetList: TArray<TMyRec>; static;
  end;

This is actually better than declaring TMyRecArr as per the code in your question. That's because the generic TArray<T> has more flexible type identity than a traditional dynamic array type. You can use TArray<T> with generic types defined in libraries that are independent and unaware of your code.

Now, you could declare the type like this:

type
  TMyRec = record
    type TMyRecArray = array of TMyRec;
    class function GetList: TMyRecArray; static;
  end;

And then your array type is TMyRec.TMyRecArray. But I urge you not to do this. You'll have a type that can only be used with you code, and cannot be used with third party code.

In summary, TArray<T> is your friend.

like image 189
David Heffernan Avatar answered Oct 13 '22 16:10

David Heffernan


Since declarations of pointers types are permitted before the type definition, slightly modifying your function you're allowed to do this:

type
  PMyRecArr = ^TMyRecArr;

  TMyRec = record
    // fields
    class procedure GetList(const arr: PMyRecArr); static;
  end;

  TMyRecArr = array of TMyRec;

The procedure implementation and its usage follow:

class procedure TMyRec.GetList(const arr: PMyRecArr);
begin
  SetLength(arr^, 4);
end;

var
  arr: TMyRecArr;

begin
  TMyRec.GetList(@arr);
  Writeln(Length(arr));//prints 4
end.
like image 26
fantaghirocco Avatar answered Oct 13 '22 16:10

fantaghirocco