4

I'm writing a kind of array wrapper, using a record as container, and including some "class-like" functions to it. I also want the possibility to assign an array to it, as with a normal array, so I have implemented a Implicit class operator:

type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper; overload;
    Items: TArray<TObject>;

    procedure Add(AItem: TObject);
    ...
  end;

So I can do things like:

procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  ...
end;

The problem appears when I try to pass an array of Integer to a method that has as parameter a TArrayWrapper:

procedure DoSomethingElse(AArrayWrapper: TArrayWrapper);
begin
    ...
end;


procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  DoSomethingElse(myArray);   <--- Works!!!!

  DoSomethingElse([Obj1, Obj2, Obj3]); <--- Error E2001: Ordinal type required -> It is considering it like a set, not as an array
end;

What could be happening?

Thank you in advance.

1
  • That's a compiler deficiency Commented May 30, 2019 at 11:47

1 Answer 1

4

The compiler has not implemented the string like operations on a dynamic array for class operators, when the record/class is used as a parameter.

There is not a QP report for this, as far as I can see. Now there is, see below.

A similar example is found in the comments here: Dynamic Arrays in Delphi XE7


A workaround:

DoSomethingElse(TArray<TObject>.Create(Obj1, Obj2, Obj3));

Or as @Stefan suggests, in order to avoid unnecessary allocations. Add a constructor to the record:

type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper; 
    constructor Init( const AArray: array of TObject);
  end;

DoSomethingElse(TArrayWrapper.Init([obj1,obj2,obj3]));

Reported as: RSP-24610 Class operators do not accept dynamic arrays passed with brackets

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

3 Comments

As a workaround I would rather suggest adding a ctor for the TArrayWrapper type with an array of TObject parameter than going through immediate dynamic array allocation and implicit operator call plus compiler added CopyRecord
@StefanGlienke, thanks. Added your suggestion to the answer. I will report this to QP later today.
I was already using this solution. The code is less elegant than just passing the array, but It works. Thank you very much.

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.