[fpc-pascal] Better way to handle callback types

Ryan Joseph genericptr at gmail.com
Sat Aug 21 20:06:34 CEST 2021


FPC has a number of function pointer types and eventually will have another in "reference to" closures. This presents a problem of how the programmer can make a function that is type agnostic so that we can use different types of callbacks.

Currently this is the best solution I can think of but it's still a real mess and tedious to setup. Here's a little snippet of a list class that has a Sort method.

It feels to me like the compiler needs a new type which wraps all the callbacks for us but maybe there's a better way?

========================================


type
  generic TSList<T> = class
  type
     TComparator = record
        private type
          TFuncProc = function (constref left, right: T; context: pointer): integer;
          TFuncNested = function (constref left, right: T; context: pointer): integer is nested;
          TFuncObject = function (constref left, right: T; context: pointer): integer of object;
        private
          index: TFuncType;
        public
          function Call(constref left, right: T; context: pointer): integer;
        case byte of
          0: (proc: TFuncProc);
          1: (nested: TFuncNested);
          2: (obj: TFuncObject);
      end;

     ...

      procedure Sort(callback: TComparator.TFuncProc; context: pointer = nil);
      procedure Sort(callback: TComparator.TFuncNested; context: pointer = nil);
      procedure Sort(callback: TComparator.TFuncObject; context: pointer = nil);
  end;

     ...

procedure TSList.Sort(callback: TComparator.TFuncProc; context: pointer);
var
  comparator: TComparator;
begin
  comparator.proc := callback;
  comparator.index := TFuncType.IsProc;
  { do sorting and call comparator.Call(left, right, context); which routes to the correct callback }
end;


Regards,
	Ryan Joseph



More information about the fpc-pascal mailing list