8.5 Generic procedures and functions

As can be seen in the syntax diagrams for generic procedures and functions, it is possible to define generic procedures and functions or generic methods. Where in a generic class type all methods of the class can contain the template, it is possible to have a non-generic class with a generic method:

uses typinfo;

type
  TMyEnum = (one,two,three);

  TTypeHelper = class(TObject)
    generic procedure PrintTypeName<T>(a : T);
  end;

generic procedure TTypeHelper.PrintTypeName<T>(a : T);
begin
  Writeln(PTypeInfo(typeInfo(T)) ˆ.name);
end;

var
  Helper : TTypeHelper;

begin
  Helper.specialize PrintTypeName<TMyEnum>(one);
end.

or, in Delphi syntax:

uses typinfo;

type
  TMyEnum = (one,two,three);

  TTypeHelper = class(TObject)
    procedure PrintTypeName<T>(a : T);
  end;

procedure TTypeHelper.PrintTypeName<T>(a : T);
begin
  Writeln(PTypeInfo(typeInfo(T)) ˆ.name);
end;

var
  Helper : TTypeHelper;

begin
  Helper.PrintTypeName<TMyEnum>(one);
end.

Both global procedures or functions can also be generic:

ses typinfo;

type
  TMyEnum = (one,two,three);

generic function GetTypeName<T>(a : T) : string;

begin
  Result:=PTypeInfo(typeInfo(T))ˆ.name;
end;

begin
  Writeln(specialize GetTypeName<TMyEnum>(one));
end.

It is even possible to use them in Delphi mode:

uses typinfo;

type
  TMyEnum = (one,two,three);

function GetTypeName<T>(a : T) : string;

begin
  Result:=PTypeInfo(typeInfo(T))ˆ.name;
end;

begin
  Writeln(GetTypeName<TMyEnum>(one));
end.

But this code is not compilable with Delphi. In delphi, the closest thing to this feature is to use a record or class with generic class methods:

uses typinfo;

type
  TMyEnum = (one,two,three);

  TTypeHelper = class(TObject)
    class procedure PrintTypeName<T>(a : T);
  end;

class procedure TTypeHelper.PrintTypeName<T>(a : T);
begin
  Writeln(PTypeInfo(typeInfo(T)) ˆ.name);
end;

begin
  TTypeHelper.PrintTypeName<TMyEnum>(one);
end.