[英]type inference based on generic argument type (Delphi)
我正在尝试编写一个接受匹配参数类型的泛型函数。
Delphi确实在普通参数的简单情况下正确地推断出类型参数。
例如:
type
TFoo = class
function Pair<T>(e1, e2: T): TList<T>;
end;
用aFoo.Pair(1, 2);
调用它aFoo.Pair(1, 2);
工作得很好,但是当我将参数签名更改为泛型类型时
type
TFoo = class
function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
end;
并试着打电话给它
aFoo.InsertInto(TList<String>.Create, 'bar');
然后编译器抱怨它:
E2010 Incompatible types: 'Generics.Collections.TList<uTest.TFoo.InsertInto.T>' and 'Generics.Collections.TList<System.String>'
有没有办法可以编写这个(或类似的)方法,以便客户端不必指定类型参数?
aFoo.InsertInto<String>(TList<String>.Create, 'bar');
我的猜测是来自Delphi的强类型性质。
uTest.TFoo.InsertInto.T
等同于System.String
但它实际上是一个不同的类型 。
就像在这个例子中Int1
和Int2
不是同一类型一样:
var
Int1: array[1..10] of Integer;
Int2: array[1..10] of Integer;
...
Int1 := Int2; // <== BOOM! E2008 Incompatible types (in XE2)
实际问题不在于类型推断,而是根据Pascal / Delphi的严格规则,类型不兼容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.