调用作为不带参数的访问类型传递的函数

时间:2013-07-22 02:44:23

标签: ada

考虑一系列不带参数且返回相同类型的函数:

function Puzzle1 return Answer_Type;
function Puzzle2 return Answer_Type;
function PuzzleN return Answer_Type;

我希望能够将这些函数传递给子程序,让子程序调用函数并使用结果。我可以通过定义访问类型将函数传递给子程序:

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;     -- expected type "Answer_Type", found type "Answer_Func_Type"
   Result := Func();   -- invalid syntax for calling a function with no parameters
   -- ...
end Print_Result;

有没有办法在Ada中执行此操作而不向函数添加伪参数?

1 个答案:

答案 0 :(得分:12)

您试图使用指向函数的指针,而不是函数本身。取消引用指针,一切都应该很好:

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;