Andreas Rejbrand
Andreas Rejbrand

Reputation: 109168

Reference to overloaded function (or procedure)

I use the type

type
  TRealFunction = reference to function(const X: extended): extended;

a lot in my code. Suppose I have a variable

var
  rfcn: TRealFunction;

and try to assign Math.ArcSec to it:

rfcn := ArcSec;

This works just as expected in Delphi 2009, but now I tried to compile it in Delphi 10.2, and the compiler gets upset:

[dcc32 Error] Unit1.pas(42): E2010 Incompatible types: 'TRealFunction' and 'ArcSec'

The difference, it seems, is that ArcSec is overloaded in Delphi 10.2: it comes in single, double, and extended flavours. It seems like the compiler doesn't like references to overloaded functions (or procedures) of this kind (too similar types?).

However, if I redefine

type
  TRealFunction = function(const X: extended): extended;

it compiles just fine.

Of course, there are obvious workarounds here: I could define

function ArcSec(const X: extended): extended; inline;
begin
  result := Math.ArcSec(X);
end;

or I could just write

rfcn := function(const X: extended): extended
  begin
    result := Math.ArcSec(x);
  end;

Still, this is a lot of code to write. Is there a simpler workaround?

Upvotes: 6

Views: 303

Answers (1)

LU RD
LU RD

Reputation: 34947

This works:

type
  TRealFunction = function(const X: extended): extended;
const
  rc : TRealFunction = Math.ArcSec;
type
  TRealFunctionRef = reference to function(const X: Extended) : Extended;

var
  rfcn: TRealFunctionRef;
begin
  rfcn := rc;
  ...

It requires an extra type declaration, but perhaps it is worth the effort.

Upvotes: 4

Related Questions