【问题标题】:Ada: Importing the inequality operator "/="Ada:导入不等式运算符“/=”
【发布时间】:2021-02-22 18:42:11
【问题描述】:

我不想use 整个包,但我确实想导入一些功能,例如"/=" 运算符。我知道renames 允许我使用大多数函数来执行此操作,但是使用不等式运算符我得到了错误explicit definition of inequality not allowed。如何在不引发错误的情况下导入此运算符?

package Integer_Maps is new Ada.Containers.Ordered_Maps
(
 Key_Type => Integer,
 Element_Type => Integer
);

-- the next line fails!
function "/=" ( Left, Right: Integer_Maps.Cursor ) return Boolean
   renames Integer_Maps."/=";

【问题讨论】:

  • “不允许显式重载不等式运算符”,LRM83 6.7 第 4 段。
  • @SimonWright 我在下面的回答中引用了 2012 LRM 6.6,但我发现他们在随后的 LRM 中删除/改写了这句话很有趣。

标签: import package operator-overloading ada inequality


【解决方案1】:

您可以使用use type Integer_Maps.Cursor; 来显示类型上的运算符。

对于容器游标,执行use all type Integer_Maps.Cursor; 也可能是实际的,它可以显示类型上的所有原始操作,例如KeyElement

我通常将use typeuse all type 子句放在需要它们的最里面的封闭范围(即子程序内部)中,如下所示:

   procedure Foo is
       use all type Integer_Maps.Cursor; 
   begin
       for Cursor in My_Map.Iterate loop
          Ada.Text_IO.Put_Line
            (Integer'Image(Key(Cursor)) & " ->" & Integer'Image(Element(Cursor)));
       end loop;
   end Foo;

【讨论】:

  • 谢谢。我昨天试过了,但 gnat 不喜欢在全局范围内使用两种不同的 Cursor 类型。我今天晚些时候在家时会再试一次。
【解决方案2】:

你没有!无论如何,不​​是直接的。将等式运算符重命名为"=",就可以免费得到不等式了。

-- this line succeeds!
function "=" ( Left, Right: Integer_Maps.Cursor ) return Boolean
   renames Integer_Maps."=";

这类似于覆盖运算符。请参阅ARM 6.6,尤其是静态语义

【讨论】:

  • 你也可以use type Integer_Maps.Cursor;
  • @egilhh 谢谢;我不知道,但如果我使用多个容器,会导致名称出现问题吗?
  • 不,名称应该没有问题。由于您不知道use type,我已经提交了一个关于它的答案(和use all type
猜你喜欢
  • 2010-11-05
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2013-12-25
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多