Leon
Leon

Reputation: 105

Delphi - Implicit typecast operator not working for method parameters

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.

Upvotes: 4

Views: 515

Answers (1)

LU RD
LU RD

Reputation: 34919

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

Upvotes: 4

Related Questions