4

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)

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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...

2 Comments

I would like to return a reference to the class not a reference to an instantiated object.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.