Sign in Join

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

Mailing lists / fpc-pascal / 2013-09

generic class helper and class references

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

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

Xiangrong Fang

Hi There,

While playing with generics (ref. class inheritance and type incompatibility), I have an idea to use "generic class helper" to overcome the problem that generic methods cannot be "virtual" (because the compiler see specialized class different than the generic one?)

I have a TTree generic class (ref:
https://github.com/xrfang/fpcollection/blob/master/src/units/tree.pas), which currently has problem with the Clone method, I did the following:

type
  generic TTree<T> = class
    ... ...
  end;
  TTreeType = class of TTree;
  TTreeHelper = class helper for TTreeType;

The compiler does not compile because it thinks you cannot use a class reference (TTreeType) while defining a class helper. Why? Shouldn't class references has same effect as a Class?

Ok, since it does not compile, I changed the last line to the following alternatives, but NONE of them compiles:

1) TTreeHelper = class helper for TTree;
2) generic TTreeHelper<T> = class helper for TTree<T>;

My purpose is that since the Clone method cannot be virtual (because descendant class will not have same return type as the generic class), I try to write a class helper for ALL specialized TTree and their descendants.

Of course I can (and will) follow Sven's advice in that email to modify my TTree class. This email is just two other questions:

1) is it possible to define class helper for generic classes?
2) why class helper require a class and we cannot use a class reference?

Best Regards,
Xiangrong

Sven Barth
to Xiangrong Fang
Xiangrong Fang wrote 5 lines
type generic TTree<T> = class ... ... end; TTreeType = class of TTree;

This is illegal code and compiled by pre-2.7.1 FPC only because of bugs in the generic implementation. "TTree" is not a legal type outside of the generic's declaration or implementation (and no, TTree<T> is neither).

1) is it possible to define class helper for generic classes?

No. I recently had the thought to allow this as well, but not now.

2) why class helper require a class and we cannot use a class reference?

A class helper always work on variables (or return values) of the type you specified. So if you'd be able to define a class helper for TTreeType you'd only be able to use it on variables of type TTreeType or e.g. TTreeType(Self.ClassType), but not on instances of TTree.

Regards,
Sven