Sunday, March 1, 2020

Use a Function as a Parameter in Another Function

Use a Function as a Parameter in Another Function In Delphi, procedural types (method pointers) allow you to treat procedures and functions as values that can be assigned to variables or passed to other procedures and functions. Heres how to call a function (or procedure) as a parameter of another function (or procedure) : Declare the function (or procedure) that will be used as a parameter. In the example below, this is TFunctionParameter.Define a function that will accept another function as a parameter. In the example below this is DynamicFunction type   Ã‚   TFunctionParameter function(const value : integer) : string;...function One(const value : integer) : string;begin   Ã‚   result : IntToStr(value) ; end;function Two(const value : integer) : string;begin   Ã‚   result : IntToStr(2 * value) ; end;function DynamicFunction(f : TFunctionParameter) : string;begin   Ã‚   result : f(2006) ; end;...//Example usage: var   Ã‚   s : string; begin   Ã‚   s : DynamicFunction(One) ;   Ã‚   ShowMessage(s) ; //will display 2006   Ã‚   s : DynamicFunction(Two) ;   Ã‚   ShowMessage(s) ; // will display 4012end; Important Notes Of course, you decide on the signature of the TFunctionParameter: whether it is a procedure or a function, how many parameters does it take, etc.If TFunctionParameter is a method (of an instance object) you need to add the words of object to the procedural type name, as in:TFunctionParameter function(const value : integer) : string of object;If you expect nil to be specified as the f parameter, you should test for this using the Assigned function.Fixing the Incompatible type: method pointer and regular procedure

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.