@ALLIGATOR yes, you can do that too, with the exception that your code does not use the
opaque invoke, which is quite the reason of function references. My demo shows invoke to be triggered both as getter and setter and 100% cross-compatible.
Your code is still useful for 3.2.2, though, but you must explicitly call method1.
My code also works on 3.2.2, but you must
implement the invoke
function in the
interface and comment out the TFunc and call invoke explicitly, like you do, too:
This example stays Delphi compatible and is for
3.2.x:
program counter;
// this is for freepascal before function references were supported
// invoke must be expicitly called, like in ALLIGATOR'S code.
// it stays Delphi compatible.
{$ifdef fpc}{$mode delphi}{$endif}
type
ICount = interface // can't derive from TFunc here
['{472C4D07-1A7E-4D75-8A87-46417BCA8008}']
Function Invoke:Integer;overload; // Must be added to interface
Procedure Invoke(const Value:integer);overload;
end;
TCounter = Class(TInterfacedObject,ICount)
private
FValue:integer;
public
function Invoke:integer;overload;
procedure Invoke(const value:integer);overload;
end;
function TCounter.Invoke:integer;
begin
Result := FValue;
inc(FValue);
end;
procedure TCounter.Invoke(const value:integer);
begin
FValue := Value;
end;
var
Count:ICount;
i:integer;
begin
// cumbersome explicit calls, but still useful.
Count := TCounter.Create as ICount;
Count.Invoke(100); // explicitly calls invoke, starts from 100
writeln(Count.Invoke());//100 // explict call
writeln(Count.Invoke());//101 // explicit call
Count.Invoke(1000);// explicit call, starts from 1000
writeln(Count.Invoke());// 1000
writeln(Count.Invoke());//1001
count.Invoke(-9);
for i := 0 to 9 do write(count.Invoke():3);
readln;
end.
https://forum.lazarus.freepascal.org/index.php/topic,74842.msg589230.html#msg589230Examine the difference and see why function references can be very useful.
Same technique, different, longer, notation....
I did not even use anonymous functions in my first example, because that follows from invoke() in trunk and delphi.
I hope it documents the variable capture a bit more clearly.