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

Ale*_*nov 7 delphi generics type-inference delphi-xe

我正在尝试编写一个接受匹配参数类型的泛型函数.
Delphi确实在普通参数的简单情况下正确地推断出类型参数.

例如:

type
  TFoo = class
    function Pair<T>(e1, e2: T): TList<T>;
  end;
Run Code Online (Sandbox Code Playgroud)

调用它aFoo.Pair(1, 2);可以很好地工作,但是当我将参数签名更改为泛型类型时

type
  TFoo = class
    function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
  end;
Run Code Online (Sandbox Code Playgroud)

并试着打电话给它
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');

Fra*_*ois 5

我的猜测是来自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)
Run Code Online (Sandbox Code Playgroud)

实际问题不在于类型推断,而是根据Pascal/Delphi的严格规则,类型不兼容.

  • 它也可能是字符串文字"bar"的类型不是"System.String" - 至少现在还没有.字符串文字的类型相当流畅; 编译器会为它分配它需要的任何类型,至少在知道它需要什么类型时.考虑如何将相同的字符串文字作为UnicodeChar,PAnsiChar,WideString或ShortString传递,所有这些都来自代码中的相同文本.因此,'uTest.TFoo.InsertInto.T`实际上代表了六种不同的类型,编译器无法选择"最佳"类型. (2认同)