9

I want to sort my generic tobjectlist using the built-in sort method.

here is what I do:

//create the list object
myList := TObjectList<MyType>.Create(false);   

[...] //populate the list with unsorted entries

//sort the list
myList.sort(@Comparer);

[...]//store sorted results back to array

myList.Destroy;

my Comparer function looks like this:

function Comparer(Item1, Item2 : pointer):integer;
begin
  result := myCompare(item1, item2);
end;

According to the specs, it should work like this.

I get an compiler error E2250 No overloaded version of 'Sort' exist with these parameters (exact wording differs, i use a non english version of RAD Studio)

I have no idea why this should not be valid Pascal - does anyone of you have insight to share on this?

Johan
  • 74,508
  • 24
  • 191
  • 319
sum1stolemyname
  • 4,506
  • 3
  • 26
  • 44
  • Although Leonardo and I offered more detail, Rob's answer is the most useful to you. The compiler generally gives clear reasons why it objects to something. – David Heffernan Jan 24 '11 at 18:53

3 Answers3

9

You are almost there. Since I don't know what MyType is you may need to change the call to your myCompare function.

myList.Sort(TComparer<MyType>.Construct(
   function (const L, R: MyType): integer
   begin
     result := myCompare(L, R);
   end
));
Leonardo Herrera
  • 8,388
  • 5
  • 36
  • 66
6

TObjectList<T>.Sort is declared as:

procedure Sort(const AComparer: IComparer<T>);

IComparer<T> is defined as:

IComparer<T> = interface
  function Compare(const Left, Right: T): Integer;
end;

You are instantiating TObjectList<MyType> and so you need to pass an IComparer<MyType> to Sort. In order to do this you will need an object to provide a concrete implementation of that interface.

One obvious way to do this would be to subclass TObjectList<MyType> and implement the interface there.

Another way to do this is to use TComparer<T> to create an IComparer<T> on demand using its Construct class function. You would need to supply a comparison function:

TComparison<T> = reference to function(const Left, Right: T): Integer;

Leonardo's answer demonstrates how to do this.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
4

If the compiler says no overloaded version exists with that parameter type, ask yourself what overloads do exist. Check the source code or the documentation to find out.

There you'll see that TObjectList<T> inherits two Sort methods from TList<T>. One takes no arguments, and the other takes a reference to something implementing the IComparer<T> interface. Your standalone function doesn't fit that. Write a descendant of TComparer<MyType> and override its Compare method.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467