无法理解泛型是如何工作的

Can't understand how generics work

我有一个名为 Linked_List(.ads) 的程序包,这是其中的代码:

Generic
   type T is private;
package Linked_List is
   type List is tagged record
       Data : T;
   end record;
end Linked_List;

这是包中包含主要功能的代码 (main.adb)

with Ada.Text_IO; use Ada.Text_IO;
with Linked_List;
procedure Main is
  type ListOfIntegers is new Linked_List(T => Integer);
begin
   null;
end Main;

我收到此错误:

4:30 subtype mark required in this context 
found "Linked_List" declared at linked_list.ads:3
found "Linked_List" declared at linked_list.ads:3
4:41 incorrect constrain for this kind of type

感谢任何帮助。

new Linked_List(T => Integer) 定义了新的 package,而不是新的 type。您收到的错误消息是因为编译器认为您正在声明一个类型,因此在第 30 列看到包的名称将其混淆;它想查看(子)类型的名称。

第 4 行应为

package ListOfIntegers is new Linked_List(T => Integer);

后面还有一个类型ListOfIntegers.List,所以可以写成

My_List : ListOfIntegers.List;

您可能会发现不得不一直说 ListOfIntegers. 很烦人;你可以说

use ListOfIntegers;

之后你可以写

My_List : List;

但通常认为最好不要过度(如果你有几十个“withed”包,“使用”它们会让你很难知道你指的是哪一个)。

顺便说一下,Ada 的正常用法是使用下划线来分隔标识符中的单词:List_Of_Names.