[Lazarus] two questions about generics

Sven Barth pascaldragon at googlemail.com
Fri Feb 22 12:04:00 CET 2013


On 22.02.2013 04:48, Xiangrong Fang wrote:
> Hi all,
>
> I have two questions about generics.  I am writing a two-dimensional
> table class. Say:
>
> type
>    generic TTable<TValue> = class
>    ... ...
>    public
>      constructor Create(ADefaultValue: TValue);
>    end;
>
> My questions are:
>
> 1) if I am not writing a generic class I can define default value for
> the constructor, i.e.
>
> constructor Create(ADefaultValue: Double = 0);
>
> for generic classes, how can I define a default value?

You can use the new intrinsic Default(TypeName) which is available in 
FPC 2.7.1. Your declaration would look like this:

=== snippet begin ===

constructor Create(ADefaultValue: TValue = Default(TValue));

=== snippet end ===

You need to pay attention though with what you specialize TTable. You 
can't use a record for example, because records can not have default 
values in parameters (this has nothing to do with generics or the 
Default() intrinsic). Classes and interfaces are ok they as are all 
primitive types.

As a sidenote: Default() can not only be used in constructor parameter 
lists, but also for normal functions and in normal code. Using it in 
const sections or var sections does not yet work in every case 
(primitive types work, classes, interfaces, records and objects do not).

>
> 2) if I cannot define a default value, I hope to do so while
> specializing it. i.e.
>
> type
>    TNumericTable = specialize TTable<Double>
>    public
>      constructor Create(ADefaultValue: Double = 0); override;
>    end;
>
> That is, can I "inherit" a generic class while specializing it?

You would need to write it this way:

=== code begin ===

type
   TNumericTable = class(specialize TTable<Double>)
   public
     constructor Create(ADefaultValue: Double = 0);
   end;

constructor TNumericTable.Create(ADefaultValue: Double);
begin
   inherited Create(ADefaultValue);
end;

=== code end ===

Regards,
Sven




More information about the Lazarus mailing list