What is the use case for constructor constraints in Delphi?

The name pretty much is ...

Why do you want to use constructor constraint?

This is explicitly implied by the class constraint.

If you use it alone, you cannot do anything with the thing you created.

Why does he exist?

Additional Information:

Like the note, the following code does not compile until you add a constructor constraint:

 program Project3; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type TSomeClass<T: class> = class function GetType: T; end; { TSomeClass<T> } function TSomeClass<T>.GetType: T; begin Result := T.Create; end; begin try { TODO -oUser -cConsole Main : Insert code here } except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. 
+4
source share
2 answers

Why do you want to use constructor constraint?

This is explicitly implied by a class restriction.

No no. A constructor constraint requires the type to have an open constructor with no parameters, and then allows this constructor to be called.

Not all classes have an open constructor without parameters.

+8
source

IMHO, the official reason for this limitation is that the compiler cannot handle this on its own.

This is just a flag for the compiler, which can also be set on its own, because the compiler really recognizes the fact that we need a constructor constraint. Therefore, the compiler can automatically process it, because the Generic class will be compiled before using this class.

Maybe we will get it with XE9

UPDATE

If TComponent is accepted as a class type without an open constructor without parameters, then the constructor constraint is useless, because this (extended sample from Nick) compiles and instantiates TComponent. Of course, it will not call the original TComponent.Create constructor (AOwner: TComponent), instead TObject.Create is called, but you have an instance of TComponent.

 program Project3; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, System.Classes; type TSomeClass<T: class, constructor> = class function GetType: T; end; { TSomeClass<T> } function TSomeClass<T>.GetType: T; begin Result := T.Create; end; var SomeClass : TSomeClass<TComponent>; Component : TComponent; begin try SomeClass := TSomeClass<TComponent>.Create; Component := SomeClass.GetType; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. 

UPDATE

 TSomeClass<T: class, constructor> 

has the same meaning as

 TSomeClass<T: constructor> 

because the record may have a constructor, but not without parameters, so we have an implicit restriction on the class. And turning it around

 TSomeClass<T: class> 

may have an implicit constructor constraint

+2
source

Source: https://habr.com/ru/post/1445507/


All Articles