Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Delphi generic class descend from its class argument?

I've been trying to define a generic, inheritable TSingleton class. Here's what I had in progress:

  TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom)
  strict private
    class var FInstance : RealClass;
  protected
    procedure InstanceInitialization;virtual;
  public
    destructor Destroy; override;
    class procedure Create; reintroduce;
    class function Instance : RealClass;
    class procedure InstanceFree;
  end;

The goal was to be able to "insert" the singleton pattern in an inheritance tree. so instead of declaring something like this :

  TMySingletonComponent = class(TComponent)

  end;

And need to implement the singleton pattern there, I would declare something like this :

  TMyGenericSingletonComponent = class(TSingleton<TMyGenericSingletonComponent,TComponent>)
  end;

Sadly, this won't work. I'm getting the following error(In D2010):

  TSingleton<RealClass, InheritsFrom : class> = class(InheritsFrom) ///E2021 Class type required

Now I was wondering, would this work in Delphi XE? Is there some "clean hack" I could use to make this work in D2010? Is there some fundamental reasons why this can't work?

like image 838
Ken Bourassa Avatar asked Dec 29 '22 06:12

Ken Bourassa


1 Answers

By design, you can't create a generic class which derives from one of its type arguments.

like image 145
Barry Kelly Avatar answered Dec 31 '22 13:12

Barry Kelly