[fpc-pascal] Compatibility of very similar generic types
Sven Barth
pascaldragon at googlemail.com
Thu Aug 18 17:26:27 CEST 2016
Am 18.08.2016 15:09 schrieb "Felipe Monteiro de Carvalho" <
felipemonteiro.carvalho at gmail.com>:
>
> On Thu, Aug 18, 2016 at 2:44 PM, Sven Barth <pascaldragon at googlemail.com>
wrote:
> > generic procedure WriteVector_To_DM<T>(ADest: TDataManager; ASelf:
> > specialize TVector<T>);
> > generic procedure ReadVector_From_DM<T>(AFrom: TDataManager; var ASelf:
> > specialize TVector<T>);
> >
> > and use them like this:
> >
> > specialize WriteVector_To_DM<TSubClass1>(...);
>
> Aha, great, didn't know we had something in this direction. But
> correct me if I am wrong, but this wouldn't work in my case, because
> my function writes the class to a stream in the end of it, so it needs
> to know which type T is. If the type is TSomeClass or a descendent,
> then it will write each field of the class to the stream.
>
> But in a generic class/function there is no way to ask if T is an int,
> or is an TSomeClass, or am I missing some way of writing code that is
> different for various possible types?
You can enforce that T needs to be a subclass of TSomeClass by declaring it
as "T: TSomeClass"; like this:
generic procedure WriteVector_To_DM<T: TSomeClass>(ADest: TDataManager;
ASelf: specialize TVector<T>);
In that case the compiler knows that T will at least be a TSomeClass so you
can use methods and fields of it without problems.
Note: these generic constraints also work for generic types and is already
in 3.0.0 for them.
Additionally you can play around with TypeInfo() which works on variables
of a generic type as well.
Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160818/d40dd204/attachment.html>
More information about the fpc-pascal
mailing list