1

Is there a way to make something like this work?

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TMyRecord = record
    class operator Explicit(const a: array of integer): TMyRecord;
  end;

{ TMyRecord }

class operator TMyRecord.Explicit(const a: array of integer): TMyRecord;
begin
end;

var
  a: array[0..100] of integer;
begin
  TMyRecord(a);  //Incompatible types: 'array of Integer' and 'array[0..100] of Integer
end.

"TMyRecord.Explicit(const a: TIntegerDynArray)" works for TIntegerDynArray, but I can't get static arrays to work.

0

3 Answers 3

3

It works (well, compiles ) if you declare your static array as a type:

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type 
  TMyArray = array[0..100] of Integer;  

  TMyRecord = record 
    class operator Explicit(const a: TMyArray): TMyRecord; 
  end; 

class operator TMyRecord.Explicit(const a: TMyArray): TMyRecord; 
begin 
end; 

var 
  a: TMyArray; 

begin 
  TMyRecord(a); 
end;

end.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but in our case the arrays can have different sizes.
2

I'd say that is a compiler bug/limitation and that you have no way around it.

I tried using Slice like this:

TMyRecord(Slice(a, Length(a)));

which results in this compiler error:

E2193 Slice standard function only allowed as open array argument

So the compiler doesn't recognise that the explicit operator is expecting an open array parameter.

A plain method call rather than an operator is fine which further leads me to believe that the compiler is simply not going to play ball.

If you can't use open arrays then there is no clean way out for you.

Comments

0

An alternative is to cast to a pointer-type via the address of the variable :

type 
  PMyRecord = ^TMyRecord;

// ...

begin
  PMyRecord(@a).DoWhatever;
end;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.