Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function passed as an access type that takes no parameters

Tags:

ada

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?

like image 814
Theran Avatar asked Jul 22 '13 02:07

Theran


1 Answers

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;
like image 61
NWS Avatar answered Sep 22 '22 20:09

NWS