[fpc-pascal] returning a generic object?

Sven Barth pascaldragon at googlemail.com
Thu Sep 12 07:25:06 CEST 2013


Am 12.09.2013 04:03 schrieb "Xiangrong Fang" <xrfang at gmail.com>:
>
> Hi All,
>
> I have this generic class:
>
> type
>   generic TTree<T> = class
>   private
>     FItems: TList;
>     ... ...
>   public
>     Data: T;
>     ... ...
>     function FirstChild: TTree;
>     ... ...
>   end;
>
> function TTree.FirstChild: TTree;
> begin
>   if FItems.Count = 0 then Exit(nil);
>   Exit(TTree(FItems[0]));
> end;
>
> when using it, I did:
>
> type
>   TStringTree = specialize TTree<string>;
>
> It generated a compilation error:
>
> Error: Incompatible types: got "TTree" expected "TTree$AnsiString"
>
> on the line "Exit(TTree(FItems[0]));" of function FirstChild.
>
> And I tried to change it to:
>
> Exit(TTree<T>(FItems[0]));
>
> But is not accepted.
>
> How to solve this? thanks.

Could be one of the things I fixed in 2.7.1. Otherwise try the following as
a workaround:

=== code begin ===

type
  generic TTree<T> = class
   public type
     TSelfType = TTree;
  private
    FItems: TList;
    ... ...
  public
    Data: T;
    ... ...
     function FirstChild: TSelfType;
    ... ...
  end;

function TTree.FirstChild: TSelfType;
begin
  if FItems.Count = 0 then Exit(nil);
  Exit(TSelfType(FItems[0]));
end;

=== code end ===

I've not tested it though. Just an idea that it might work.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130912/3932320a/attachment.html>


More information about the fpc-pascal mailing list