Search code examples
delphigenerics

Generics constructor with parameter constraint?


TMyBaseClass=class
  constructor(test:integer);
end;

TMyClass=class(TMyBaseClass);

TClass1<T: TMyBaseClass,constructor>=class()
  public
    FItem: T;
    procedure Test;
end;

procedure TClass1<T>.Test;
begin
  FItem:= T.Create;
end;

var u: TClass1<TMyClass>;
begin
  u:=TClass1<TMyClass>.Create();
  u.Test;
end;

How do I make it to create the class with the integer param. What is the workaround?


Solution

  • Just typecast to the correct class:

    type
      TMyBaseClassClass = class of TMyBaseClass;
    
    procedure TClass1<T>.Test;
    begin
      FItem:= T(TMyBaseClassClass(T).Create(42));
    end;
    

    Also it's probably a good idea to make the constructor virtual.