Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"As" operator for constrained generic types

Consider:

TTest <T : class, constructor> = class 
public
  function CreateMyObject : T;
end;
function TTest<T>.CreateMyObject : T;
var
  Obj : TObject;
begin
  Obj := T.Create; 
  Result := (Obj as T);
end;

Why isn't this possible? Compiler yields an "Operator not applicable to this type" error message for the as operator. T is constrained to be a class type, so this should work, shouldn't it?

Thanks for the help.

like image 629
jpfollenius Avatar asked Mar 19 '26 01:03

jpfollenius


2 Answers

I ran into the same problem and solved it by adding a low-level pointer-copy method to the class as a workaround:

  TTest <T : class, constructor> = class
  private
    function _ToGeneric(AItem: TObject): T; inline; //inline, so it's a little faster
  public
    function CreateMyObject : T;
  end;

  function TTest<T>.CreateMyObject : T;
  var
    Obj : TObject;
  begin
    Obj := T.Create;
    Result := _ToGeneric(Obj);
  end;

  function TTest<T>._ToGeneric(AItem: TObject): T;
  begin
    System.Move(AItem,Result,SizeOf(AItem))
  end;
like image 187
MvdH Avatar answered Mar 22 '26 04:03

MvdH


This is a known issue with the Delphi compiler. Please vote for it if you'd like to see it fixed. In the meantime, you can work around it by saying

Result := (Obj as TClass(T));
like image 41
Mason Wheeler Avatar answered Mar 22 '26 04:03

Mason Wheeler