枚举类型的 Ada 向量

Ada vector of enumerated type

我试图在 Ada 中创建一个枚举类型的向量,但编译器似乎期望相等函数重载。我如何告诉编译器只使用默认的 equal 函数。这是我拥有的:

package HoursWorkedVector is new Ada.Containers.Vectors(Natural,DAY_OF_WEEK);
--where Day of week is defined as an enumeration

当我尝试编译时,我收到消息:

no visible subprogram matches the specification for "="

我是否需要创建一个比较函数来获得枚举类型的向量?提前致谢。

编译器自动选择预定义的相等运算符:

with
  Ada.Containers.Vectors;

package Solution is
   type Day_Of_Week is (Work_Day, Holiday);

   package Hours_Worked_Vector is
     new Ada.Containers.Vectors (Index_Type   => Natural,
                                 Element_Type => Day_Of_Week);
end Solution;

Ada.Containers.Vectors的定义是这样开始的:

generic
   type Index_Type is range <>;
   type Element_Type is private;
   with function "=" (Left, Right : Element_Type)
      return Boolean is <>;
package Ada.Containers.Vectors is

通用形式函数中<>的含义由RM 12.6(10)定义:

If a generic unit has a subprogram_default specified by a box, and the corresponding actual parameter is omitted, then it is equivalent to an explicit actual parameter that is a usage name identical to the defining name of the formal.

所以如果像你在评论中所说的那样,DAY_OF_WEEK是在另一个包中定义的,那么你的实例化就相当于

package HoursWorkedVector is new Ada.Containers.Vectors(Natural, Other_Package.DAY_OF_WEEK, "=");

这不起作用,因为比较 DAY_OF_WEEK 值的 "=" 不可见。

您可以按照评论中的建议在实例化中包含 Other_Package."="。至少有三种方法可以使 "=" 可见,以便您的原始实例化可以工作:

  1. use Other_Package; 这将使 "=" 直接可见,但它也会使该包中定义的所有其他内容直接可见。这可能不是你想要的。

  2. use type Other_Package.DAY_OF_WEEK; 这使得DAY_OF_WEEK的所有运算符直接可见,包括"<""<="等,以及所有的枚举文字,以及您可能在 Other_Package 中声明的 DAY_OF_WEEK 的任何其他原始子程序。这可能是最受欢迎的解决方案,除非出于某种原因使枚举文字可见是个问题。

  3. 使用重命名声明重新定义"=":

    function "=" (Left, Right : DAY_OF_WEEK) return Boolean renames Other_Package."=";

    这使得 "=" 直接可见。