在 Ada 中,为什么孩子没有被通用父级实例化,为什么我也必须使它成为通用的?

Fin*_*005 4 generics ada instance package

我有一个带有一些通用接口的父包。我现在想创建这个接口的几个实现,每个实现在不同的文件中。我以为我可以简单地使这些包成为包含接口的包的子包,实例化泛型,然后直接访问子包,但这给了我一个错误,即子包也必须是泛型的。

这导致我进行以下实现:

parent.ads:

generic
   type T is private;

package Parent is

   type I_Generic is interface;
   type Any_Generic is access all I_Generic'Class;

   function Get (This : in out I_Generic) return T is abstract;
   procedure Set (This : in out I_Generic; Value : T) is abstract;

end Parent;
Run Code Online (Sandbox Code Playgroud)

亲子广告:

generic
package Parent.Child is

   --  long spec

   type Impl is new I_Generic with private;
   type Impl_Access is access all Impl;
   
   overriding function Get (This : in out Impl) return T;
   overriding procedure Set (This : in out Impl; Value : T);

private

   type Impl is new I_Generic with
      record
         Data : T;
      end record;

end Parent.Child;
Run Code Online (Sandbox Code Playgroud)

父子.adb:

package body Parent.Child is

   --  long body
   
   overriding
   function Get (This : in out Impl) return T is
   begin
      return This.Data;
   end Get;

   overriding
   procedure Set (This : in out Impl; Value : T) is
   begin
      This.Data := Value;
   end Set;

end Parent.Child;
Run Code Online (Sandbox Code Playgroud)

测试者.adb:

with Ada.Text_IO;
with Parent;
with Parent.Child;

package body Tester is

   package Parent_Inst is new Parent (T => Integer);
   package Child_Inst is new Parent_Inst.Child;
   
   procedure Test is
      Instance : constant Child_Inst.Impl_Access := new Child_Inst.Impl;
      Polymorphic : constant Parent_Inst.Any_Generic := Parent_Inst.Any_Generic (Instance);
   begin
      Instance.Set (42);
      Ada.Text_IO.Put_Line (Polymorphic.Get'Img);
   end Test;

end Tester;
Run Code Online (Sandbox Code Playgroud)

结果:

42
Run Code Online (Sandbox Code Playgroud)

为什么我需要使子包通用,然后首先创建它的实例?为什么我不能简单地使用Instance : Parent_Inst.Child.Impl_Access := new Parent_Inst.Child.Impl;

有什么办法可以做这个清洁工吗?也许我忽略了我的要求的不同解决方案,它更简单并且没有这个问题?或者这只是实现我所描述的内容的方法,我是否应该接受额外包实例化的冗长?在我自己的代码中,我现在必须为每个接口实现包进行几个包实例化,这会导致许多额外的代码行。

fly*_*lyx 6

由于LRM 10.1.1, 17/3,子包必须是通用的:

通用库包的子库本身要么是通用单元,要么是同一通用单元的其他子库的重命名。

这是必要的,因为子包可以访问父单元的通用参数的值,除非实例化父单元,否则该参数不存在。

现在在 Ada 中,泛型实例化是显式的,并且每个实例化只实例化一个泛型单元。在你的情况下,

package Parent_Inst is new Parent (T => Integer);
Run Code Online (Sandbox Code Playgroud)

实例化Parent包。它不是实例化Parent.Child,因为这是一个独立的通用单元。因此,您确实需要Child单独实例化。

您可以编写一个一次性实例化的帮助程序包,例如

generic
   type T is private;
package Everything is
   package Parent_Inst is new Parent (T);
   package Child_Inst is new Parent_Inst.Child;
end Everything;
Run Code Online (Sandbox Code Playgroud)

然后Everything在需要实例的地方实例化。