'在具有外部包的通用主体中不允许访问属性

'Access attribute not allowed in generic body with external package

我在 Ada 中遇到泛型问题。给定以下示例,gnatmake 结果为:

g_package.adb:13:33: 'Access attribute not allowed in generic body
g_package.adb:13:33: because access type "t_callback_p" is declared outside generic unit (RM 3.10.2(32))
g_package.adb:13:33: move 'Access to private part, or (Ada 2005) use anonymous access type instead of "t_callback_p"
gnatmake: "g_package.adb" compilation error

假设外包不能改,请问有办法解决吗?我首先得到了错误消息的原因(编译器不知道通用包的正确类型,但是当有问题的传递函数没有触及通用包的任何部分时,这有点烦人..)

g_package.adb

with Ada.Text_IO; use Ada.Text_IO;
with external;

package body g_package is
   procedure quix (f : String) is
   begin
      Put_Line ("Does a thing");
   end quix;

   procedure foo (bar : String) is
   begin
      Put_Line ("baz" & bar & Boolean'Image(flag));
      external.procedure_f (quix'Access);
   end foo;
end g_package;

g_package.ads

generic
   flag : Boolean;
package g_package is
   procedure foo (bar : String);
end g_package;

external.ads

package external is
   type t_callback_p is access procedure (s : String);
   procedure procedure_f (proc : t_callback_p);
end external;

在 Ada 中无法做到这一点。如果您希望不可移植并且正在使用(看起来)GNAT,您可以使用 GNAT 特定的属性 'Unrestricted_Access.

您可以(如错误消息中所述)移动“访问包规范的私有部分:

private with external;

generic
   flag : Boolean;
package g_package is
   procedure foo (bar : String);

private
   procedure quix (f : String);
   quix_access : constant external.t_callback_p := quix'Access;

end g_package;

并在正文中使用常量:

external.procedure_f (quix_access);