[fpc-pascal] RTTI and generics: accessing specialized class instance

Sven Barth pascaldragon at googlemail.com
Fri Oct 30 22:29:34 CET 2015


On 30.10.2015 20:10, leledumbo wrote:
> Consider the following:
>
> type
>    generic TGenClass<T> = class
>    ...
>    end;
>
>    TSpecType = specialize TGenClass<Integer>;
>
>    TMyClass = class
>      FST: TSpecType;
>      procedure p;
>    published
>      ST: TSpecType read FST write FST;
>    end;
>
> procedure TMyClass.p;
> ...
> begin
>    PropCount := GetPropList(Self,Props);
>    for i := 0 to PropCount - 1 do begin
>      Prop := Props^[i];
>      PropName := Prop^.Name;
>      case Prop^.PropType^.Kind of
>        tkObject: begin
>          Obj := GetObjectProp(Self,Prop); //1
>          ...
>        end;
>      end;
>    end;
> end;
>
> In //1, GetObjectProp will return TObject for ST property. Since generic
> types without specialization cannot be used in type declaration, how can I
> get the actual type of ST and cast Obj to it so I can access its properties?
> Note that ST here is just an example, there could be multiple TGenClass
> specialization that TMyClass uses.

TGenClass<> is not a full type, only TGenClass<Integer> is, so you need 
to use - in your example - TSpecType(Obj). In Delphi mode you could also 
use TGenClass<Integer>(Obj). For mode ObjFPC you'll need to wait till 
I've finished generic functions, cause then "specialize 
TGenClass<Integer>(Obj)" will work as well.
Note: specializations can also be declared locally in a 
procedure/function/method in a type section.

Regards,
Sven



More information about the fpc-pascal mailing list