Type Method Inference

Let's say I have a class with two common methods:

TMyClass = class procedure DoWith<T: class> (obj: T); procedure DoFor<T: class> ( proc: TProc<T> ); end; 

Now, when I want to call either of these two methods with a specific type parameter, Delphi can infer the type for the DoWith method, so I can call it with

 MyClass.DoWith <TButton> ( MyButton ) 

or

 MyClass.DoWith ( MyButton ) 

The Delphi compiler will be happy to compile both. But if I omit the type parameter in the DoFor method, the Delphi compiler complains about the missing type parameter:

 MyClass.DoFor<TButton>(procedure (Button: TButton) begin .... end); // compiles MyClass.DoFor(procedure (Button: TButton) begin .... end); // doesn't compile 

Now my question is: is this just a flaw of the compiler, or is there some logical reason (which I haven't figured out yet) that prevents the compiler from correctly DoFor type of the DoFor method?

+5
source share
1 answer

The reason that he cannot deduce T from the argument TProc<T> is because at the time TProc<TButton> is a constructed type without any information originally consisting of TProc<T> .

To do this, it would be necessary to deduce the type from the anonymous signature of the method, which does not work (I think Barry Kelly could explain this better, and I think he once wrote about the difficulties of lambda and the type of output in Delphi).

The only type of output that the Delphi compiler can use is an argument of type T. Even with several arguments that do not work often and even less if you have several parameters of the type type.

Edit: I found a comment where Barry talked a bit about the difficulties of type inference and lambdas in the Delphi compiler: http://www.deltics.co.nz/blog/posts/244/comment-page-1#comment-107

+5
source

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


All Articles