The constructor
constraint in Delphi is pretty much useless in my opinion. And it is of no real use to you since you need to create TForm
descendants and they have a constructor that receives a parameter.
You should constrain your generic type T
to derive from TForm
.
type
TgrsObj = class
class function Singleton<T: TForm>(O: T): T; static;
end;
The implementation would then be:
class function TgrsObj.Singleton<T>(O: T): T;
begin
Result := O;
if not Assigned(Result) then
Result := T(TFormClass(T).Create(nil));
end;
And since you are really just trying to access the virtual TComponent
constructor you could make the class more general like this:
type
TgrsObj = class
class function Singleton<T: TComponent>(O: T): T; static;
end;
class function TgrsObj.Singleton<T>(O: T): T;
begin
Result := O;
if not Assigned(Result) then
Result := T(TComponentClass(T).Create(nil));
end;
Of course, this forces nil
as the owner of the form instance. You will probably want to change the method to receive an owner which can then be passed to the constructor.