Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2013-09

returning a generic object?

6 messages · 3 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Xiangrong Fang

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.

Sven Barth
to Xiangrong Fang: I have this generic class: type generic TTree<T> = class private FItems: TList; ... ...…
"Xiangrong Fang" wrote 41 lines
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