views:

142

answers:

2

I have a persistence framework, and I am trying to use generics so I don't have to keep creating new list classes for each type of object I want to store in a type safe way.

I have a method that returns the class of the contained object in the list class (so I know which queries to run and which object to create.

As an example, it looks something like this:

type

  TMyObject = class

  end;
  TMyObjectClass = class of TMyObject;


  TMyObjectList = class
  public
    function ListClass: TMyObjectClass; virtual; abstract;

  end;

  TMyObjectList<T: TMyObject, constructor> = class(TMyObjectList)
  public
    function ListClass: TMyObjectClass; override;

  end;

implementation

{ TMyObjectList<T> }

function TMyObjectList<T>.ListClass: TMyObjectClass;
begin
  result := T;  //  <==== this wont compile
end;

end.

Is there a way of returning the class of the generic parameter in this case?

Thanks

N@ (using Delphi 2009)

A: 

T is not an instance of an object.

In your specific example, you should write something like:

result := self;

I think you're looking the wrong way...

vIceBerg
I would like to return a reference to the *class* not a reference to an instantiated object.
Nat
No, `T` is not an instance of an object. `T` is a class. You're confused because the **constraint** "`T: TMyObject`" looks like a variable declaration where `T` would be a `TMyObject` reference. Generics mean that classes now how *type parameters* in the same way that functions have *value parameters*.
Rob Kennedy
+5  A: 

This is a known issue in Delphi 2009. It's been fixed in 2010. I just tested it and your code compiles just fine there.

Mason Wheeler
You. Are. A. Legend. Thanks! Can't wait to get 2010 (should be tomorrow, yay!).
Nat
Cool! The enhanced RTTI will make persistence a lot easier, BTW. :)
Mason Wheeler