Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define class with self-referencing generics constraint in Delphi?

As shown in this article, one can define in C#:

public class MyTreeNode<T> where T: MyTreeNode<T>
{

}

In Delphi, however, the following code does not compile and complains "E2003 Undeclared identifier: 'MyTreeNode<>'":

type
    TMyTreeNode<T: TMyTreeNode<T>> = class
    end;

The formal terminology seems to be "self-referencing generics constraint". I wonder how to do this in Delphi ?

PS:

Another useful article as David pointed out.

Relevent SO post regarding Delphi and covariance / contravariance.

Wikipedia page of co/contra-variance.

like image 999
SOUser Avatar asked Apr 23 '14 13:04

SOUser


1 Answers

There is no way in Delphi to express such a generic constraint. Furthermore, I believe that there is no typesafe way to achieve what can be achieved in C# with such a constraint.

like image 183
David Heffernan Avatar answered Sep 28 '22 03:09

David Heffernan