2
votes

I am trying to learn Object Pascal (maybe for hobby projects), and I found that Object Pascal (FreePascal) supports generics in {$mode objfpc}. They look like C# generics, but it seems as there is a difference. When I tried to declare a variable:

uses Fgl;
...
SomeVariable: TFPSList<string>;

I've got error which said me about unexpected '<' and I removed parameter <string> and it passes compilation. So, seems that list of string's and list of int's would be declared in the same way: Something: TFPSList. But this means that Pascal treats both lists as of the same type, right? In C# and other languages type parameter modifies all type and creates new type. I know that old Pascales used containers of pointers as "generic" solution (TList, etc), but TFPSList is a real generic but in the declaration it looks like simple container of pointers. Does modern Pascal (FreePascal, Delphi) distinguish between these generic types (similar to TFPSList of int's/of string's)? If I have generic list of int's does it mean that I can pass it to the function expecting a list of another type and how/where I should check items type: compile time/runtime? I know about is and as keywords, but what to do if list is empty? How to check the type of container's items?

PS. Excuse me if the question sounds strange or stupid, I never used Pascal before.

1
Try using TFPGList. As per freepascal.org/docs-html/current/rtl/fgl/tfpslist.html, TFPSList is a base class that is not meant to be used directly (Note I haven't used either, I just googled 'TFPGList') - David A
Some time with the documentation should clear up these misunderstandings quite quickly - David Heffernan

1 Answers

3
votes

in fgl unit TFPSList is not a generic type, its a normal class so you can't specialize it, use TFPGList, your syntax is also wrong, in {$mode objfpc} you need to use specialize keyword for generic, the correct syntax is :

program Project1;

     {$mode objfpc}
    uses Classes,sysutils,fgl;
    type
    SomeType=specialize TFPGList<String>;
     var
       SomeVariable:SomeType;
    begin
      SomeVariable:=SomeType.Create;
      SomeVariable.Add('some string');
    end.

free pascal also generic in Delphi mode {$MODE Delphi} with different syntax, more information here free pascal doc