繁体   English   中英

基于泛型参数类型的类型推断(Delphi)

[英]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但它实际上是一个不同的类型

就像在这个例子中Int1Int2不是同一类型一样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM