[fpc-pascal] How to inline CompareFunc to Sort method in generic abstract class
Sven Barth
pascaldragon at googlemail.com
Sat Nov 19 22:26:49 CET 2022
Am 14.11.2022 um 19:26 schrieb Vojtěch Čihák via fpc-pascal:
> Hi,
>
> I wrote a generic abstract class - a list based on dynamic array (i.e. array of T;) and this class can be specialized elsewhere with any type (records or classes).
> Part of the class is sorting. There are more ways how to deliver *compare function* to sorting method. I can pass it as a parameter or I can define it as: function Compare(A, B: T): Integer; virtual; abstract;. But this way the function cannot be inlined.
>
> Question: Is there a way how to *inline* compare function to sorting method in this general purpose generic abstract class?
Currently there is not. But once FPC supports reusing types in other
specializations inside the generic parameter list you /should/ be able
to do the following:
=== code begin ===
program tinline;
{$mode objfpc}
type
generic TComparer<T> = class
class function Compare(aLeft, aRight: T): Integer;
end;
// this kind of constraint that uses T does not work yet
generic TList<T; Comparer: specialize TComparer<T>> = class
procedure Sort;
end;
TLongIntComparer = class(specialize TComparer<LongInt>)
class function Compare(aLeft, aRight: T): Integer; inline;
end;
class function TComparer.Compare(aLeft, aRight: T): Integer;
begin
Result := 0;
end;
procedure TList.Sort;
begin
{ sort algorithm that calls Comparer.Sort which /should/ be inlined }
end;
class function TLongInt.Compare(aLeft, aRight: T): Integer;
begin
if aLeft < aRight then
Result := -1
else if aLeft > aRight then
Result := 1
else
Result := 0;
end;
var
l: specialize TList<LongInt>;
begin
l : =specialize TList<LongInt, TLongIntComparer>.Create;
l.Sort;
end.
=== code end ===
I can't test this currently whether it would really work due to the
missing functionality, but it's at least possible.
Regards,
Sven
More information about the fpc-pascal
mailing list