Home > Software engineering >  Generics Imbrication
Generics Imbrication

Time:11-11

I have this 3 classes :

TClassA = Class(Tobject);
end;

TClassB = Class(Tobject);
  Child: TClassA;
end;

TClassC = Class(Tobject);
  Child: TClassB;  
end;

Now I need to override this hierarchy like this :

TMyClassA = Class(TClassA);
end;

TMyClassB = Class(TClassB);
  Child: TMyClassA;
end;

TMyClassC = Class(TClassC);
  Child: TMyClassB;  
end;

How can I avoid to write this second hierarchy and use instead generic in the first one? I would like to do something like TClassC<B: TClassB, A: TClassA> but I don't found how to write it

I try something like this but it's didn't work :

TClassA = Class(Tobject)
end;

TClassB<A: TClassA> = Class(Tobject)
  Child: A;
end;

TClassC<B: TClassB> = Class(Tobject)
  Child: B;
end;

CodePudding user response:

Generics are no good solution to this task.

Assuming that you don't want a second Child field in your second hierarchy because you already get the one from the base class, you better introduce a property with getter and setter to narrow the type from TClassA to TMyClassA.

TClassA = class
end;

TClassB = class ​
  ​FChild: TClassA;
  ​property Child: TClassA {getter, setter};
​end;
​
​TClassC = class
  ​FChild: TClassB;
  property Child: TClassB {getter, setter};
end;


TMyClassA = class(TClassA)
end;

TMyClassB = class(TClassB)
  property Child: TMyClassA {getter, setter};
end;

TMyClassC = class(TClassC)
  property Child: TMyClassB {getter, setter};
end;

CodePudding user response:

AFAIK, you can't use a Generic class as input to another Generic class. So you can't use TClassB as a Generic parameter for TClassC.

But, you can try something more like this instead:

TClassA = class(TObject)
end;

TClassB_Base = class(TObject)
end;

TClassB<A: TClassA> = class(TClassB_Base)
  Child: A;
end;

TClassC<B: TClassB_Base> = class(TObject)
  Child: B;
end;
TMyClassA = class(TClassA)
end;

TMyClassB = class(TClassB<TMyClassA>)
end;

TMyClassC = class(TClassC<TMyClassB>)
end;
  • Related