Function call returned by function

Having this:

procedure Foo; begin end; function Bar: TProcedure; begin Result := Foo; end; 

The following compilations:

 var tmp: TProcedure; begin tmp := Bar(); tmp(); 

... but in Delphi the following does not compile:

 Bar()(); 

Is there a reason for this "limitation"? Syntax Bar()(); compiles in some other "flavor" of Pascal? Syntax Bar()(); compiles in a different context?

+5
source share
2 answers

I do not think that there is a limitation in the grammar of the language. The statement Bar()() must be valid. So, I believe this is a compiler error in older versions of Delphi. This program compiles in Delphi 2010 and later:

 {$APPTYPE CONSOLE} uses SysUtils; procedure Foo; begin end; function Bar: TProcedure; begin Result := Foo; end; begin Bar()(); end. 

It is possible that the compiler error was fixed before Delphi 2010, this is just the version that I have to pass. It seems that the error is still present in Delphi 7 and fixed by Delphi 2010. Thus, the error seems to have been fixed somewhere between the two versions.

Update 1

Marco reports that the Free Pascal compiler accepts Bar()() .

Update 2

Rudy did some testing and reported that the error was still present in D2007, so the fix was either D2009 or D2010. My instincts tell me that Embarcadero itself would detect a problem when adding the function of anonymous methods, and that would be a trigger to fix it.

+3
source

Just call like

 TProcedure(Bar()); 
+6
source

Source: https://habr.com/ru/post/1200090/


All Articles