[fpc-pascal] Generic type parameter variable initialization

kyan alfasud.ti at gmail.com
Thu Jan 5 15:51:13 CET 2012


On Thu, Jan 5, 2012 at 4:03 PM, Florian Klämpfl <florian at freepascal.org> wrote:
> Am 05.01.2012 14:19, schrieb Sven Barth:
> Has the workaround really the same effect? I really wonder why there is
> a need for default then ...

Yes, works for Variants as well. Look at the implementation of
System._FinalizeArray() in Delphi; it handles tkVariant type kind.
Come to think of it, it can be elegantly wrapped up in the following
generic class:

type
 TDefault<T> = class
   class function Value: T; inline;
 end;

class function TDefault<T>.Value: T;
begin
 Finalize(Result);
 FillChar(Result, SizeOf(Result), 0);
end;

and used like this:

type
  TSomeRec = record
    S: string;
    V: Variant;
    I: Integer;
  end;
var
 S: string;
 I: Integer;
 V: Variant;
 X: IInterface;
 C: TObject;
 D: TDateTime;
 R: TSomeRec;
 P: Pointer;
begin
 S := 'test';
 I := 42;
 V := Date;
 D := Date;
 X := Self;
 C := Self;
 R.S := 'test1';
 R.V := Date;
 R.I := 99;
 P := Self;

 S := TDefault<string>.Value;
 I := TDefault<Integer>.Value;
 V := TDefault<Variant>.Value;
 D := TDefault<TDateTime>.Value;
 X := TDefault<IInterface>.Value;
 C := TDefault<TObject>.Value;
 R := TDefault<TSomeRec>.Value;
 P := TDefault<Pointer>.Value;
end;



More information about the fpc-pascal mailing list