枚举文字也用作参数名称

Enum literal also used as parameter name

我创建了以下示例代码:

with Ada.Text_IO;

procedure Main is
   type My_Type is
     (A,
      B,
      C);

   procedure Foo (The_Type : My_Type) is
   begin
      null;
   end Foo;

   procedure Bar (B : String) is
   begin
      -- Error
      Foo (The_Type => B);

      -- Ok
      Foo (The_Type => My_Type'Succ (A));

      -- Ok
      Foo (The_Type => My_Type'Value ("B"));
   end Bar;
begin
   Bar ("Hello");
end Main;

在枚举类型 My_Type 中定义的文字 B 也用作过程 Bar 中的参数名称。不幸的是,编译器假定在过程调用 Foo (The_Type => B); 中,B 是参数的名称,而不是定义的枚举类型中的文字 B。我找到了两个不是最佳的解决方案来解决问题。如果我对重命名文字或参数名称不感兴趣,还有其他解决方案吗?

您的问题是过程 Bar 中的参数 B 隐藏了在过程 Bar 的封闭范围中声明的枚举标识符 B。您只需要使用参数命名范围:

with Ada.Text_IO;

procedure Main is
   type My_Type is
     (A,
      B,
      C);

   procedure Foo (The_Type : My_Type) is
   begin
      null;
   end Foo;

   procedure Bar (B : String) is
   begin
      Foo (The_Type => Main.B);
   end Bar;
begin
   Bar ("Hello");
end Main;