Let's say I have a class with two generic 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 either
MyClass.DoWith <TButton> ( MyButton )
or
MyClass.DoWith ( MyButton )
The Delphi Compiler will happily 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 shortcoming of the compiler, or is there any logical reason (that I haven't figured out yet) that prohibits the compiler from correctly inferring the type for the DoFor
method?
The reason it cannot infer T
from a TProc<T>
argument is that at that time TProc<TButton>
is a constructed type without any information that it originally was a TProc<T>
.
To do that it would have to infer the type from the anonymous method signature which does not work (I guess Barry Kelly could explain that better and I think he once wrote about the difficulties of lambdas and type inference in Delphi).
The only type inference the Delphi compiler is capable of is an argument of type T. Even with multiple arguments that does not work often and even less if you have more than one generic type parameters.
Edit: I found a comment where Barry explained 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With