saastn
saastn

Reputation: 6025

How to define a parameter of type generic list with constructor constraint?

I want to define three base classes, TMyBaseClass that keeps data, TMyBaseClassList that holds a list of instances of TMyBaseClass, and TMyBaseClassReader that scrolls through a dataset and fills a TMyBaseClassList object. This is my code:

  TMyBaseClass = class
  public
    // properties
    constructor Create;
  end;

  TMyBaseClassList<T: TMyBaseClass, constructor> = class(TObjectList<TMyBaseClass>)
  public
    function AddNew: T;
  end;

  TMyBaseClassReader<T: TMyBaseClass> = class
  public
    class procedure ReadProperties(const DataSet: TCustomADODataSet;
      const Item: T); virtual; abstract;
    class procedure ReadDataSet(const DataSet: TCustomADODataSet;
      const List: TMyBaseClassList<T>);// <- E2513
  end;

...

constructor TMyBaseClass.Create;
begin
  inherited;
end;

function TMyBaseClassList<T>.AddNew: T;
begin
  Result := T.Create;
  Add(Result);
end;

class procedure TMyBaseClassReader<T>.ReadDataSet;
var
  NewItem: T;
begin
  while not DataSet.Eof do
  begin
    NewItem := List.AddNew;
    ReadProperties(DataSet, NewItem);
    DataSet.Next;
  end;
end;

Then I want to derive child classes and only implement ReadProperties method. But I'm getting an E2513 error:

E2513 Type parameter 'T' must have one public parameterless constructor named Create

What is the problem and how can I fix it?

Upvotes: 1

Views: 1221

Answers (1)

David Heffernan
David Heffernan

Reputation: 613572

The error means that the compiler cannot be sure that T meets the requirements. Declare the derived class like so

TMyBaseClassReader<T: TMyBaseClass, constructor>

Upvotes: 4

Related Questions