[英]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.