[fpc-pascal] Generic type parameter variable initialization

kyan alfasud.ti at gmail.com
Thu Jan 5 11:57:35 CET 2012


Hello everybody.

I am new to FPC/Lazarus and I am trying to port some Delphi XE code
that uses the units Generics.Defaults and Generics.Collections so I
have to write these units for FPC because they do not exist and the
code I am porting relies heavily on them. In this process I have come
across various issues with Delphi/FPC generic compatibility but I have
managed to overcome most of them.

In a method of a generic class I need to initialize a variable of type
"T" (the generic class type parameter) with the type T's "default"
value, which is 0 for ordinal types, '' for strings, nil for
pointers/classes/interfaces, Unassigned for Variants etc. In Delphi
there is the "compiler magic" function Default() and you can write:

procedure TMyClass<T>.SomeMethod;
var
  V: T;
begin
  ...
  V := Default(T);
  ...
end;

This does not compile in FPC. Is there an alternative in FPC for the
function Default()? I suppose one could do this:

procedure TMyClass<T>.SomeMethod;
var
  V: T;
begin
  ...
  Finalize(V);
  FillChar(V, SizeOf(V), 0);
  ...
end;

which is equivalent but it doesn't look too elegant. I am using FPC
2.7.1 for Win32/64.

Thank you in advance,

Constantine.



More information about the fpc-pascal mailing list