[fpc-devel] generic constraints...

Martin Frb lazarus at mfriebe.de
Fri Jul 25 13:44:21 CEST 2025


Currently you can't do

type
   generic TFoo<A> = class
      procedure Bar; virtual;
   end;

   generic FooChild<F: TFoo> = class(F)
      procedure Bar; override;
   end;

However, without giving the TFoo you can't do the "Bar; override", 
because it wont know that the base class has a virtual Bar method.

In many case you can make the first class non generic.
But if you have several generics like that and they all take base 
classes as generic param, in order to then do something like
TFinal = class(
    specialize TBase1<
      specialize TBase2<
          specialize TBase3<TSomething>
      >
    >
)
end;

Then they all must be generics....
So in that case it would be nice to allow the generic as constraint.

---------------------------

On a related note, if building classes like that, there is another 
problem...

   generic TClassExtender<B: class> = class(B)
      constructor Create; // override
      // same for other methods
   end;
    constructor TClassExtender.Create;
    begin
      inherited;
      MyInit;
   end;


the  base class used in specialization may have a constructor that takes 
arguments....
Then you can't override/reintroduce those, because you don't yet know 
all the base classes.

It would be nice to have something (idea wise / not syntax wise)
   generic TClassExtender<B: class> = class(B)
      generic override constructor Create; // override
      // same for other methods
   end;

That would create the same constructor for each version the base class has.
- call the correct inherited
- have the same code around the inherit

Not sure if this should be limited for virtual/override / or be for any 
method.
(same for ordinary methods)





More information about the fpc-devel mailing list