我正在尝试使用 Delphi 10 Seattle 并尝试创建我的第一个通用容器类。我需要通用比较器的帮助
这是我创建的一个简单的 Hash 对象:
type
TsmHeap<T> = class
private
fList: TList<T>;
Comparer: TComparer<T>;
procedure GetChildren(ParentIndex: integer; var Child1, Child2: integer);
function GetParent(ChildIndex: integer): integer;
function GetCapacity: integer;
function GetCount: integer;
function MustSwap(iParent, iChild: integer): boolean;
procedure SetCapacity(const Value: integer);
public
constructor Create(aComparer: TComparer<T>); overload;
constructor Create(aComparer: TCOmparer<T>; aCapacity: integer); overload;
destructor Destroy; override;
//-- Methods & Functions
function Dequeue: T;
procedure Enqueue(Item: T);
function IsEmpty: boolean;
//-- Properties
property Count: integer read GetCount;
property Capacity: integer read GetCapacity write SetCapacity;
end;
我已经为这些方法编写了代码,它可以自行编译,没有任何问题。但是,当我尝试创建该类的整数版本时,我无法对其进行编译。
有问题的代码是:
iHeap := TsmHeap<integer>.Create(TComparer<integer>.Construct(
function(const Left, Right: integer): integer
begin
result := Sign(Left - Right);
end)
);
这给出了“E2250 没有可以使用这些参数调用的‘Create’的重载版本”
我做错了什么?如何创建比较器?
最佳答案
TComparer<T>.Construct
返回 IComparer<T>
- 它是一个类函数而不是构造函数。只需更改 TsmHeap<T>.Create
的参数类型即可至 IComparer<T>
它应该有效。
关于delphi - 将自定义比较器传递给 Delphi 中的通用创建过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240327/