Calling a function passed as an access type that does not require parameters

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 would like to pass these functions to a subroutine and call the function subroutine and use the result. I can pass the function to the routine by specifying the type of access:

 type Answer_Func_Type is access function return Answer_Type; 

However, there seems to be no way to actually call the passed 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 any way to do this in Ada without adding a dummy parameter to the functions?

+4
source share
1 answer

You tried to use a pointer to a function, not a function. Expand the pointer and everything should be fine:

 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; 
+12
source

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


All Articles