[Lazarus] two questions about generics

Xiangrong Fang xrfang at gmail.com
Fri Feb 22 10:31:52 CET 2013


Thanks Sven.  In the case I use Default() does it mean it always has fixed
defaults with specific types, e.g. 0 for integer '' for string. Or I can
set my own default value?

2013/2/22 Sven Barth <pascaldragon at googlemail.com>

> 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
>
> --
> ______________________________**_________________
> Lazarus mailing list
> Lazarus at lists.lazarus.**freepascal.org<Lazarus at lists.lazarus.freepascal.org>
> http://lists.lazarus.**freepascal.org/mailman/**listinfo/lazarus<http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20130222/ed5aa601/attachment-0003.html>


More information about the Lazarus mailing list