Consider a family of functions that take no arguments and return the same type:
function Puzzle1 return Answer_Type;
function Puzzle2 return Answer_Type;
function PuzzleN return Answer_Type;
I'd like to be able to pass those functions to a subprogram and have the subprogram call the function and use the result. I can pass the function to the subprogram by defining an access type:
type Answer_Func_Type is access function return Answer_Type;
However, there doesn't seem to be a way to actually call the passed-in function to get the result:
procedure Print_Result(Label : in String;
Func : in not null Answer_Func_Type;
Expected : in Answer_Type) is
Result : Answer_Type;
begin
Result := Func; -- expected type "Answer_Type", found type "Answer_Func_Type"
Result := Func(); -- invalid syntax for calling a function with no parameters
-- ...
end Print_Result;
Is there a way to do this in Ada without adding a dummy parameter to the functions?
You were trying to use the pointer to a function, not the function itself. Dereference the pointer and all should be well:
procedure Main is
type Answer_Type is new Boolean;
function Puzzle1 return Answer_Type is
begin return True;
end Puzzle1;
type Answer_Func_Type is access function return Answer_Type;
procedure Print_Result(Label : in String;
Func : in not null Answer_Func_Type;
Expected : in Answer_Type) is
Result : Answer_Type;
begin
Result := Func.all; -- You have a pointer, so dereference it!
end Print_Result;
begin
Print_Result ("AAA",Puzzle1'Access, True);
end Main;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With