Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Delphi methods with ambiguous parameter types leads to unexpected execution

Tags:

delphi

I have two Equal method that take these overloads:

TVariantExpression = reference to function(): Variant;

function Equal(const value: Variant): TRuleBuilder; overload;
function Equal(expr: TVariantExpression): TRuleBuilder; overload;

suppose I have another function :

function TForm1.GetMagicNumber: Variant;
begin
  Result := 10;
end;

and I invoke function like this:

Equal(Form1.GetMagicNumber);

After inspecting, I get result that second overload is called. Why? because both of them is valid to be called.

like image 919
Niyoko Avatar asked Dec 28 '12 09:12

Niyoko


People also ask

When a function is overloaded is ambiguous?

In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two correctly overloaded functions. This situation is said to be ambiguous. Ambiguous statements are error-generating statements and the programs containing ambiguity will not compile.

What is overload in Delphi?

Simply put, overloading is declaring more than one routine with the same name. Overloading allows us to have multiple routines that share the same name, but with a different number of parameters and types.


2 Answers

Form1.GetMagicNumber

is ambiguous. It can be either the function, or the value returned after executing the function. In most contexts, only one of those meanings is valid, and that meaning is chosen.

In your code, either meaning is valid. In such a scenario the language rules mean that the procedural type interpretation is chosen.

To force function invocation write:

Form1.GetMagicNumber()

This is a significant difference from most other languages, e.g. C, C++, C#, Java, Python etc. In those languages you must use parentheses in order to invoke a function.

like image 63
David Heffernan Avatar answered Nov 09 '22 03:11

David Heffernan


it is because the first Equal Function have the same type parameter of the second Equal function !

When you do $ ( TVariantExpression = reference to function(): Variant; ) the TVariantExpression take the Variant type as value.

like image 41
Oussaki Avatar answered Nov 09 '22 04:11

Oussaki