[英]type inference based on generic argument type (Delphi)
I'm trying to write a generic function that accepts matching parameter types. 我正在尝试编写一个接受匹配参数类型的泛型函数。
Delphi does infer the type parameter correctly in the simple case of plain arguments. Delphi确实在普通参数的简单情况下正确地推断出类型参数。
eg: 例如:
type
TFoo = class
function Pair<T>(e1, e2: T): TList<T>;
end;
calling this with aFoo.Pair(1, 2);
用aFoo.Pair(1, 2);
调用它aFoo.Pair(1, 2);
works perfectly fine, but when I change the parameter signature to a generic type 工作得很好,但是当我将参数签名更改为泛型类型时
type
TFoo = class
function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
end;
and try to call it 并试着打电话给它
aFoo.InsertInto(TList<String>.Create, 'bar');
then the compiler complains about it: 然后编译器抱怨它:
E2010 Incompatible types: 'Generics.Collections.TList<uTest.TFoo.InsertInto.T>' and 'Generics.Collections.TList<System.String>'
Is there any way I can write this (or a similar) method, so that the client doesnt have to specity the type parameter? 有没有办法可以编写这个(或类似的)方法,以便客户端不必指定类型参数?
aFoo.InsertInto<String>(TList<String>.Create, 'bar');
My guess is that comes from the strongly typed nature of Delphi. 我的猜测是来自Delphi的强类型性质。
uTest.TFoo.InsertInto.T
is equivalent to System.String
but it's actually a different type . uTest.TFoo.InsertInto.T
等同于System.String
但它实际上是一个不同的类型 。
Much like in this example where Int1
and Int2
are not of the same type: 就像在这个例子中Int1
和Int2
不是同一类型一样:
var
Int1: array[1..10] of Integer;
Int2: array[1..10] of Integer;
...
Int1 := Int2; // <== BOOM! E2008 Incompatible types (in XE2)
The actual problem is not with type inference but with the types not being compatible per the strict rules of Pascal/Delphi. 实际问题不在于类型推断,而是根据Pascal / Delphi的严格规则,类型不兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.