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.
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;
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With