使用范围作为索引的数组的索引类型是什么?

时间:2018-07-31 13:02:05

标签: ada

给出以下数组定义:

type A is array (1 .. 10) of INTEGER;

以及以下通用名称:

generic
   type LENGTH_T is range <>;
   type INDEX_T is (<>);
   type ELEMENT_T is limited private;
   type ARRAY_T is array (INDEX_T) of ELEMENT_T;
function LIST_IMAGE
  (LENGTH : in LENGTH_T;
   ITEMS  : in ARRAY_T)
   return STRING;

是否可以为LIST_IMAGE实例化A?我需要输入什么索引类型?

function ARRAY_IMAGE is new LIST_IMAGE
  (LENGTH_T  => NATURAL,
   INDEX_T   => ???,
   ELEMENT_T => INTEGER,
   ARRAY_T   => A);

3 个答案:

答案 0 :(得分:6)

解决方案是,匿名整数范围始终成为Integer子类型:

with Ada.Text_IO;

procedure Range_Of_Universal_Integer is

   type A is array (1 .. 10) of Integer;

   generic
      type Length_T is range <>;
      type Index_T is (<>);
      type Element_T is limited private;
      type Array_T is array (Index_T) of Element_T;
   function List_Image (Length : in Length_T;
                        Items  : in Array_T) return String;

   function List_Image (Length : in Length_T;
                        Items  : in Array_T) return String is
      pragma Unreferenced (Length, Items);
   begin
      return "Hello";
   end List_Image;

   subtype A_Lengths is Integer range 0 .. A'Length;
   subtype A_Range   is Integer range A'Range;

   function Image is
     new List_Image (Length_T  => A_Lengths,
                     Index_T   => A_Range,
                     Element_T => Integer,
                     Array_T   => A);

begin
   Ada.Text_IO.Put_Line (Image (Length => 0,
                                Items  => A'(others => 0)));
end Range_Of_Universal_Integer;

答案 1 :(得分:1)

Jacob已经给出了完整的答案,但想添加一个替代的子类型声明:

type A is array (1 .. 10) of Integer;

subtype A_Lengths is Integer range 0 .. A'Length;
subtype A_Range   is Integer range A'Range;

function Image is
     new List_Image (Length_T  => A_Lengths,
                     Index_T   => A_Range,
                     Element_T => Integer,
                     Array_T   => A);

答案 2 :(得分:0)

通过为数组索引创建命名子类型来简化问题。

=FORMAT((DATAINSECONDS/3600)/24; "HH:mm:ss")