Generics

From Free Pascal wiki
Jump to navigationJump to search

Introduction

Generics are native implementation of class templates. Generics are sometimes called parametrized types. FPC have official support for generics since version 2.2.

Examples

Generic class is defined using keyword generic before class name and use in class declaration: <delphi>type

 generic TList<T> = class
   Items: array of T;
   procedure Add(Value: T);
 end;</delphi>

Example of generic class implementation: <delphi>implementation

procedure TList.Add(Value: T); begin

 SetLength(Items, Length(Items) + 1);
 Items[Length(Items) - 1] := Value;

end;</delphi>

Generic class can be simply specialized for particular type by use specialize keyword. <delphi>Type

 TIntegerList = specialize TList<Integer>;
 TPointerList = specialize TList<Pointer>;
 TStringList = specialize TList<string>;</delphi>

fgl unit

fgl unit is prototype unit for base system generic classes. So far it contains few basic classes:

  • TFPGList
  • TFPGObjectList
  • TFPGInterfacedObjectList
  • TFPGMap

Technical details

1. The compiler parses a generic, but instead of generating code it stores all tokens in a token buffer inside the PPU file.

2. The compiler parses a specialization; for this it loads the token buffer from the PPU file and parses that again, but replaces the generic parameters (in most examples "T") by the particular given type (e.g. LongInt, TObject). The code basically appears as if the same class had been written as the generic but with T replaced by the given type.

Therefore in theory there should be no speed differences between a "normal" class and a generic one.

See also

External links