[fpc-devel] Is this supposed to work (generic)?

Sven Barth pascaldragon at googlemail.com
Mon Mar 27 22:59:58 CEST 2023


Am 26.03.2023 um 13:30 schrieb Martin Frb via fpc-devel:
> 3.2.3 and 3.3.1 on Win 64bit
>
> Trying a generic linked list.
> So the specialized class must have an entry for the "next" element. 
> And that entry is of the same type as the class itself.
>
> Now at first, this seems to be not possible using generics, because 
> specialize does not allow to pass in the "partially done" class.
> (the 2 commented lines produce "Error: Illegal expression")
> Only it does work, if the class is forward declared.
>
> So is it supposed to work?
> And if it is in the last case, then what about the other two cases?
>
>
> program Project1;
> type
>   generic GenLinkedList<D, T> = class
>     Data: D;
>     Next: T;
>   end;
>
>   //TBar = specialize GenLinkedList<integer, TBar>;
>   //TFoo = class(specialize GenLinkedList<integer, TFoo>);
>
>   TSome = class;
>   TSome = class(specialize GenLinkedList<integer, TSome>);
> begin
> end.
>
>
> Btw, it is the same, if the linked list uses actual pointer.
>
>   generic GenLinkedList<D, T> = class
>     type  PT = ^T;
>   public
>     Data: D;
>     NextPtr: PT;
>   end;

The correct way to declare a generic linked list using classes is the 
following:

=== code begin ===

type
   generic TGenLinkedList<D> = class
     Data: D;
     Next: specialize TGenLinkedList<D>;
   end;

   TSome = specialize TGenLinkedList<Integer>;

=== code end ===

Regards,
Sven


More information about the fpc-devel mailing list