比较枚举值

Compare Enum Values

我想遍历数组并检查当前数组索引是否为枚举值。数组和枚举定义如下:

type Option is (None, A, B, C, D);
type Votes is array(Option) of Natural;

Zero_Option_Distribution: constant Votes := (others => 0);
Votes_Distribution: Votes := Zero_Option_Distribution;

循环看起来像这样:

for I in Voting_System.Votes_Distribution'Range loop
   -- this is where I would like to check whether I is a representation of either of the enum values
end loop;

我已经尝试了我想到的所有方法,比如

if I = Voting_System.Option(None) then -- ...

if I'Val("None") then -- ...

还有一些其他版本都不起作用。

我真的没有更多的想法来实现这个。

-- this is where I would like to check whether I is a representation of either of the enum values

根据您问题中的这一行,我假设 Party 是 Integer 子类型之类的?你应该可以使用这样的东西:

-- (Checks if I is 0)
if (Integer(I) = Voting_System.Option'Pos(Voting_System.Option.None)) then
-- ...

您可以像比较任何其他类型的对象一样比较枚举类型的对象的值,使用 =:

if I = None then
   ...
end if;

如果 Party 是一个独特的类型,根据 ARM95 3.5.1 §7 和 ARM95 Annex K §175 你可以尝试这样的事情:

  for I in Votes_Distribution'Range loop
     case Party'Pos (I) is
     when Option'Pos (None) => Put_Line (I'Img & " is for «None»");
     when Option'Pos (A)    => Put_Line (I'Img & " is for «A»");
     when Option'Pos (B)    => Put_Line (I'Img & " is for «B»");
     when Option'Pos (C)    => Put_Line (I'Img & " is for «C»");
     when Option'Pos (D)    => Put_Line (I'Img & " is for «D»");
     when others            => Put_Line ("I not in Option");
     end case;
  end loop;

在所有情况下都需要其他,因为我们转而使用类型Universal_Integer.