【问题标题】:Passing a Custom Comparer to a Generic Create Procedure in Delphi将自定义比较器传递给 Delphi 中的通用创建过程
【发布时间】:2016-03-26 20:09:08
【问题描述】:

我正在试验 Delphi 10 Seattle 并尝试创建我的第一个 Generic Container 类。我需要通用比较器的帮助

这是我创建的一个简单的 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' 的重载版本”

我做错了什么?如何创建比较器?

【问题讨论】:

  • Sign 没有任何用处,而且很浪费。此外,减法很容易溢出。这是实现比较器的错误方法。

标签: delphi generics delphi-10-seattle


【解决方案1】:

TComparer&lt;T&gt;.Construct 返回IComparer&lt;T&gt; - 它是一个类函数而不是构造函数。只需将TsmHeap&lt;T&gt;.Create 的参数类型更改为IComparer&lt;T&gt; 即可。

【讨论】:

  • 另外:我认为私有字段Comparer 需要相同的类型IComparer&lt;T&gt;。但是没有理由存储它,因为 TList 可以存储比较器本身。
猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2017-11-27
  • 2020-03-08
相关资源
最近更新 更多