簡體   English   中英

可以為受約束和不受約束的 arrays 聲明通用 function 嗎?

[英]Possible to declare generic function for both constrained and unconstrained arrays?

假設我有一個正式的數組類型和一個 function 來查找該數組中給定元素的索引,如下所示:

generic
   type T is private;
   type T_index is (<>);
   type T_array is array(T_index range <>) of T;
function FindIndexGeneric(array: T_array; element: T; elementFound: out Boolean) return T_index;

為不受約束的數組(例如字符串)實例化它可以正常工作:

function FindIndexString is new FindIndexGeneric
  (T=>Character, T_index=>Positive, T_array=>String);

但是當我有一個約束數組時,這同樣不起作用:

type userIDIndex is Integer range 1..6;
type userID is array(userIDIndex) of Character;
function FindIndexUserID is new FindIndexGeneric
  (T=>Character, T_index=>userIDIndex, T_array=>userID);
-- error: expect unconstrained array in instantiation of "T_array"

我可以通過將正式的數組聲明行更改為以下內容來使約束 arrays 工作:

type T_array is array(T_index) of T;

但是我不能用這個實例化無約束的 arrays。

鑒於我的數組函數 ( FindIndexGeneric ) 中的核心邏輯是相同的,我不想創建它的多個版本,每個版本都用於受約束和不受約束的 arrays。

有沒有辦法讓通用 function 在受約束和不受約束的 arrays 上運行?

我不認為有一種方法可以用受約束和不受約束的 arrays 來實例化泛型,但是有一種解決方法:您可以使用不受約束的數組進行實例化,並定義不受約束的數組類型的受約束子類型,並且然后您可以使用受約束子類型的參數調用實例化的泛型 function。 像這樣:

generic
   type T is private;
   type T_index is (<>);
   type T_array is array (T_index range <>) of T;
...
type userIDIndex is Integer range 1..6;
type userIDUnconstrained is
   array (userIDIndex range <>) of Character;
subtype userID is userIDUnconstrained (userIDIndex);

function FindIndexUserID is new FindIndexGeneric
  (T       => Character,
   T_index => userIDIndex,
   T_array => userIDUnconstrained);

然后您可以使用約束(子)類型用戶 ID 的參數調用 FindIndexUserID。 但是,請注意,在泛型的主體中,您應該通過遍歷數組參數的索引范圍 (arry'Range) 來遍歷數組參數,而不是遍歷整個 T_index。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM