views:

593

answers:

1

I made a custom TObjectList descendant designed to hold subclasses of a base object class. It looks something like this:

interface
   TMyDataList<T: TBaseDatafile> = class(TObjectList<TBaseDatafile>)
   public
      constructor Create;
      procedure upload(db: TDataSet);
   end;

implementation

constructor TMyDataList<T>.Create;
begin
   inherited Create(true);
   self.Add(T.Create);
end;

I want each new list to start out with one blank object in it. It's pretty simple, right? But the compiler doesn't like it. It says:

"Can't create new instance without CONSTRUCTOR constraint in type parameter declaration" I can only assume this is something generics-related. Anyone have any idea what's going on and how I can make this constructor work?

+5  A: 

You're trying to create an instance of T via T.Create. This doesn't work because the compiler doesn't know that your generic type has a parameterless constructor (remember: this is no requirement). To rectify this, you've got to create a constructor constraint, which looks like this:

<T: constructor>

or, in your specific case:

<T: TBaseDatafile, constructor>
Konrad Rudolph
Bah. In this case, the compiler *does* know that TBaseDataFile has a virtual constructor that takes no parameters.
Mason Wheeler
@Mason: I can't speak for Delphi, and in general you're right that the compiler *could* know if it just looked at the right place. However, this is just not how it works, in order to to make the code more explicit.C++ is another story: it doesn't require such constraints in comparable cases.
Konrad Rudolph