RT @NPORadio2: Het nationaal vrouwenbasketbalteam onder 20 dreigt het EK in Roemenië mis te lopen, tenzij de inzamelingsactie van Iris geno… 1 hour ago
If you can read German and ever need to explain number or set theory to your kids, use this thread by isotopp… wiert.me/2023/02/02/if-…4 hours ago
RT @liekemarsman: maar vertel me nog eens waarom een snelweg bezetten om aandacht te vragen voor fossiele subsidies een slecht idee was htt… 5 hours ago
Generics and constraints in Delphi is still a bit of pain.
A while ago, I needed a factory for threads. It was more convoluted than I meant it to be, so I had a short chat with Stefan Glienke.
He came up with an example similar to the one below. I tore it apart so you can on each line see what the compiler dislikes.
This fails, but was kind of how I wanted it to be:
type
TFactory = record
class function Manufacture<T: TBaseClass, constructor>(parameter definitions): T;
end;
class function Manufacture<T: TBaseClass, constructor>(parameter definitions): T;
begin
Result := T.Create(parameter values);
end;
type
TComponentFactory = class
class function CreateComponent<T: TComponent>(AOwner: TComponent): T; static;
end;
class function TComponentFactory.CreateComponent<T>(AOwner: TComponent): T;
var
ComponentClass: TComponentClass;
Component: TComponent;
begin
ComponentClass := T;
Component := ComponentClass.Create(AOwner); // you can't do `T.Create(AOwner)`
Result := T(Component); // you can't do `Result := ComponentClass.Create(AOwner);`
end;
The usage:
var
Component: TButton;
Owner: TComponent;
begin
Owner := Application.MainForm;
Component := TComponentFactory<TButton>.CreateComponent(Owner);
Component.Parent := Owner;
end;
In the mean time, Spring4D has added the [Archive.is] Spring4D: TActivator record with many CreateInstance methods that allow you to create instances of classes for which you just have type information.
–jeroen
This fails:
type
TFactory = record
class function Manufacture<T: TBaseClass, constructor>(parameter definitions): T;
end;
class function Manufacture<T: TBaseClass, constructor>(parameter definitions): T;
begin
Result := T.Create(parameter values);
end;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Leave a Reply