Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
Andreas Rejbrand Avatar asked Jan 20 '18 13:01

Andreas Rejbrand


People also ask

When you call an overloaded function How does compiler identify the right one?

At compile time, the compiler chooses which overload to use based on the types and number of arguments passed in by the caller. If you call print(42.0) , then the void print(double d) function is invoked. If you call print("hello world") , then the void print(std::string) overload is invoked.

How do you call an overloaded function in C++?

Unlike all other overloaded operators, you can provide default arguments and ellipses in the argument list for the function call operator. The function call a(5, 'z', 'a', 0) is interpreted as a. operator()(5, 'z', 'a', 0) . This calls void A::operator()(int a, char b, ...) .

What is procedure overloading?

Overloading a procedure means defining it in multiple versions, using the same name but different parameter lists. The purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by name.


1 Answers

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.

like image 110
LU RD Avatar answered Oct 13 '22 16:10

LU RD